2015-09-16 9 views
0

Мой ящик навигации отстает при открытии сложного вида. Вот мой MenuActivity код:Медленный навигационный ящик

public class MenuActivity extends AppCompatActivity implements View.OnClickListener { 

private DrawerLayout mDrawer; 
private Toolbar toolbar; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_menu); 
    // Set a Toolbar to replace the ActionBar. 
    toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); 

    // Set the menu icon instead of the launcher icon. 
    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

    // Setup drawer view 
    findViewById(R.id.building_status_fragment).setOnClickListener(this); 
    findViewById(R.id.news_fragment).setOnClickListener(this); 
    findViewById(R.id.register_fragment).setOnClickListener(this); 
    findViewById(R.id.phone_view).setOnClickListener(this); 
    findViewById(R.id.services_fragment).setOnClickListener(this); 
    findViewById(R.id.contacs_fragment).setOnClickListener(this); 
    // first init 
    getFragmentManager().beginTransaction().replace(R.id.container, new BuildingStatusFragment()).commit(); 
    setTitle(getString(R.string.title_building_progress)); // toolbar.setTitle dont work, hm 
} 

@Override 
public void onClick(View v) { 
    mDrawer.closeDrawers(); 
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); 
    switch(v.getId()) { 
     case R.id.building_status_fragment: 
      fragmentTransaction.replace(R.id.container, new BuildingStatusFragment()); 
      toolbar.setTitle(getString(R.string.title_building_progress)); 
      break; 
     case R.id.news_fragment: 
      fragmentTransaction.replace(R.id.container, new NewsFeedFragment()); 
      toolbar.setTitle(getString(R.string.title_news)); 
      break; 
     case R.id.register_fragment: 
      fragmentTransaction.replace(R.id.container, new RegisterFragment()); 
      toolbar.setTitle(getString(R.string.title_look)); 
      break; 
     case R.id.services_fragment: 
      fragmentTransaction.replace(R.id.container, new ServicesFragment()); 
      toolbar.setTitle(getString(R.string.title_services)); 
      break; 
     case R.id.contacs_fragment: 
      fragmentTransaction.replace(R.id.container, new ContactsFragment()); 
      toolbar.setTitle(getString(R.string.title_contacts)); 
      break; 
     case R.id.phone_view: 
      startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:74996782873"))); 
      break; 
    } 
    fragmentTransaction.commit(); 
} 



@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case android.R.id.home: 
      // https://stackoverflow.com/questions/13721049/how-to-hide-default-keyboard-when-click-on-menu 
      if(getCurrentFocus() != null && getCurrentFocus() instanceof EditText){ 
       InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
       imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
      } 
      mDrawer.openDrawer(GravityCompat.START); 
      return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

}

У меня есть "сложный" вид с 2 изображениями:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="@color/white" 
android:scrollbars="none"> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="#fff"> 

     <ImageView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_centerInParent="true" 
      android:adjustViewBounds="true" 
      android:src="@drawable/auto" /> 

     <TextView 
      android:id="@+id/toptext" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentTop="true" 
      android:layout_marginLeft="17dp" 
      android:layout_marginTop="17dp" 
      android:background="#B300A3DA" 
      android:paddingLeft="6dp" 
      android:paddingRight="6dp" 
      android:text="Покупка" 
      android:textColor="#fff" 
      android:textSize="18sp" /> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/toptext" 
      android:layout_marginLeft="17dp" 
      android:layout_marginTop="4dp" 
      android:background="#B300A3DA" 
      android:paddingLeft="6dp" 
      android:paddingRight="6dp" 
      android:text="машиномест" 
      android:textColor="#fff" 
      android:textSize="18sp" /> 

     <!--Костыль--> 
     <LinearLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentBottom="true" 
      android:layout_centerHorizontal="true" 
      android:paddingBottom="15dp"> 
      <!--Костыль--> 
      <LinearLayout 
       android:id="@+id/auto_form" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:background="#B3000000" 
       android:orientation="vertical" 
       android:paddingBottom="7dp" 
       android:paddingLeft="50dp" 
       android:paddingRight="50dp" 
       android:paddingTop="7dp"> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="center_horizontal" 
        android:text="Посмотреть" 
        android:textColor="@color/white" 
        android:textSize="18sp" /> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="center_horizontal" 
        android:text="предложение" 
        android:textColor="@color/white" 
        android:textSize="18sp" /> 
      </LinearLayout> 
     </LinearLayout> 
    </RelativeLayout> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="#fff"> 

     <ImageView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_centerInParent="true" 
      android:adjustViewBounds="true" 
      android:src="@drawable/rights" /> 

     <TextView 
      android:id="@+id/toptext2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentTop="true" 
      android:layout_marginLeft="17dp" 
      android:layout_marginTop="17dp" 
      android:background="#B300A3DA" 
      android:paddingLeft="6dp" 
      android:paddingRight="6dp" 
      android:text="Оформление" 
      android:textColor="#fff" 
      android:textSize="18sp" /> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/toptext2" 
      android:layout_marginLeft="17dp" 
      android:layout_marginTop="4dp" 
      android:background="#B300A3DA" 
      android:paddingLeft="6dp" 
      android:paddingRight="6dp" 
      android:text="прав собственности" 
      android:textColor="#fff" 
      android:textSize="18sp" /> 
     <!--Костыль--> 
     <LinearLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentBottom="true" 
      android:layout_centerHorizontal="true" 
      android:paddingBottom="15dp"> 
      <!--Костыль--> 
      <LinearLayout 
       android:id="@+id/rights_form" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:background="#B3000000" 
       android:orientation="vertical" 
       android:paddingBottom="7dp" 
       android:paddingLeft="50dp" 
       android:paddingRight="50dp" 
       android:paddingTop="7dp"> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="center_horizontal" 
        android:text="Посмотреть" 
        android:textColor="@color/white" 
        android:textSize="18sp" /> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="center_horizontal" 
        android:text="предложение" 
        android:textColor="@color/white" 
        android:textSize="18sp" /> 
      </LinearLayout> 
     </LinearLayout> 
    </RelativeLayout> 

</LinearLayout> 

И запаздывает каждый раз, когда я открываю этот фрагмент. Также я заметил, что фрагмент с видом карты также имеет некоторые задержки. Я читаю this post и выглядит так, как будто я должен выполнить всю свою работу после того, как ящик навигации закрыт (если я вызову mDrawer.closeDrawers() до того, как транзакция фрагмента не такая же?), Но какая причина отставания, если я открываю ящик, когда фрагмент со сложным представлением уже инициализирован? Это очень странно для меня.

Также отладчик сказал, что uithread занимает 2 работы и пропускает кадры. Так что я должен оптимизировать свои «сложные» фрагменты или оптимизировать навигационный ящик? И как? Thx

ответ

2

Я видел ваш код и следующие поправки Я хочу сделать

  1. Загрузка растровых изображений Офф-Ui Thread (вместо упоминания больших растровых изображений в XML использовать держатель место и начать загрузку в на резюме)
  2. Используйте масштабированную версию растровых изображений, если это возможно
  3. Вы можете загружать растровые изображения в формате RGB565, если они не прозрачны, это будет половину размера растрового изображения практически без потери качества.
  4. Не задавайте цвет фона для своей относительной компоновки. Он никогда не будет отображаться, так как изображение перегрузит его. Overdrawing потребляет вычислительную мощность. Это поможет вам ускориться.

    1. Избегайте ненужных вложений ваших макетов. Линейный внутри Линейный, вместо этого попробуйте RelativeLayout или PercentRelativeLayout

    2. Попробуйте использовать getWindow(). SetBackgroundDrawable (null); как вы установили белый цвет ScrollView.

Я надеюсь, что это достаточно, чтобы ускорить ваш код вверх.

+0

Thx! Таким образом, единственный способ исправить мой код в фрагментах, чтобы сделать ящик для навигации открытым гладко? И в моем фрагменте просмотра карты я также должен попытаться переместить всю загрузку в фоновый поток? –

+0

Вы можете вызвать getMapAsync для карт Google, и вы должны предоставить обратный вызов onMapReady. Вы будете уведомлены, когда карта будет загружена (готова к использованию) –

+0

Печально, но я все еще не могу понять, почему тогда ящик навигации отстает, если я открою меню, когда фрагмент уже загружен? –

Смежные вопросы