0

我在應用中添加了導航視圖和抽屜佈局。當我打開和關閉抽屜時,它會滯後。慢慢打開和關閉。我也在6.0版本中突出顯示了這個問題,但不像4.4那樣突出。導航抽屜需要時間打開和關閉

當我4.4設備上運行,我打開我注意到日誌消息太多的工作可以在主線程上做抽屜。

所以,我想評論的所有代碼,除了導航抽屜和選項菜單代碼。所以之後我發現它工作得很好。

這是問題嗎?或者一些內存問題可以在那裏?但在更大的存儲設備上,我也發現了這個問題。

我需要爲其他代碼另一個活動?這樣抽屜工作會更快嗎?

我也試圖創建一個片段並且在主活性的FrameLayout代替它以分離的代碼。但它仍然滯後。

如果我創建新的活動我仍然需要在該活動的所有導航代碼,這將是再次同樣的事情。

我不明白可能是什麼問題。任何人都可以請幫助..謝謝..

這裏是代碼:

public class MainActivity extends AppCompatActivity implements GetContactsAsyncTask.ContactGetCallBack,UpdateUserAsyncTask.UpdateUserCallBack { 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     contactDb = new ContactTableHelper(MainActivity.this); 
     mDb = new UserTableHelper(MainActivity.this); 

     boolean result = Utility.checkAndRequestPermissions(MainActivity.this); 

     LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, 
       new IntentFilter(REGISTRATION_COMPLETE)); 
     LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, 
       new IntentFilter(PUSH_NOTIFICATION)); 

     NotificationUtils.clearNotifications(getApplicationContext()); 


     sharedpreferences = getSharedPreferences("UserProfile", Context.MODE_PRIVATE); 

     mUserId = sharedpreferences.getString("userId", ""); 

     firstTimeLogin = sharedpreferences.getBoolean("login", false); 

     refreshedToken = sharedpreferences.getString("deviceId", ""); 

     parentLayout = (LinearLayout) findViewById(R.id.toolbar_container); 

     setupView(); 

     mUser = new User(); 

     url = sharedpreferences.getString("url", ""); 

     contactList = new ArrayList<Contact>(); 

     txtuserName = (TextView) findViewById(R.id.txtusername); 
     txtmobile = (TextView) findViewById(R.id.txtmobile); 
     profileImageView = (CircleImageView) findViewById(R.id.thumbnail); 

     if (profileImageView != null) { 
      profileImageView.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        drawerLayout.closeDrawers(); 
        Intent Intent = new Intent(MainActivity.this, ProfileActivity.class); 
        Intent.putExtra("user", mUser); 
        Intent.putExtra("url", url); 
        startActivity(Intent); 
       } 
      }); 
     } 

     BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
     Bitmap bitmap = BitmapFactory.decodeFile(image.getPath(), bmOptions); 

     if (bitmap != null) { 
      profileImageView.setImageBitmap(bitmap); 
     } else { 
      profileImageView.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_account_circle_white_48dp)); 
     } 

     ImageView sync = (ImageView) findViewById(R.id.sync); 

     sync.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       contactList.clear(); 
       contactDb.deleteAllContacts(); 

       GetContactsAsyncTask getContactsAsyncTask = new GetContactsAsyncTask(MainActivity.this, MainActivity.this, mUserId, MainActivity.this); 
       getContactsAsyncTask.execute(mUserId); 

      } 
     }); 
    } 

    void setupView() { 
     File sd = Environment.getExternalStorageDirectory(); 
     image = new File(sd + "/Profile", "Profile_Image.png"); 

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

     navigationView = (NavigationView) findViewById(R.id.navigation_view); 


     navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { 

      @Override 
      public boolean onNavigationItemSelected(MenuItem menuItem) { 
       drawerLayout.closeDrawers(); 
       menuItem.setChecked(true); 

       FragmentManager fragmentManager = getSupportFragmentManager(); 

       switch (menuItem.getItemId()) { 

        case R.id.nav_menu_contacts: 
         fragmentManager.beginTransaction().replace(R.id.container, fragment).commit(); 

         break; 

        case R.id.nav_menu_settings: 

         Intent i = new Intent(MainActivity.this, PreferencesActivity.class); 
         i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
         startActivity(i); 

         break; 

        case R.id.nav_log_out: 

         SharedPreferences pref = getSharedPreferences("UserProfile", MODE_PRIVATE); 
         SharedPreferences.Editor editor = pref.edit(); 
         editor.remove("UserUsername"); 
         editor.remove("userId"); 
         editor.remove("url"); 
         editor.remove("login"); 
         editor.remove("company"); 
         editor.remove("emailId"); 
         editor.remove("profileImage"); 
         editor.remove("fullName"); 
         editor.remove("homeAddress"); 
         editor.remove("workAddress"); 
         editor.remove("workPhone"); 
         editor.remove("pass"); 
         editor.remove("jobTitle"); 
         editor.remove("mobileNo"); 
         editor.commit(); 

         mDb.deleteAllUsers(); 
         contactDb.deleteAllContacts(); 
         UpdateTokenAsyncTask updateTokenAsyncTask = new UpdateTokenAsyncTask(MainActivity.this, mUserId, ""); 
         updateTokenAsyncTask.execute(mUserId, ""); 

         finish(); 
         i = new Intent(MainActivity.this, LoginActivity.class); 
         i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 
         i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
         startActivity(i); 

         break; 

        case R.id.nav_invite: 

         i = new Intent(MainActivity.this, InviteContactsActivity.class); 
         i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
         startActivity(i); 

         break; 
       } 
       return true; 
      } 
     }); 

     Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar); 
     TextView mTitle = (TextView) findViewById(R.id.toolbar_title); 

     final ImageView menu = (ImageView) findViewById(R.id.menu); 

     menu.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       PopupMenu popup = new PopupMenu(MainActivity.this, menu); 

       popup.getMenuInflater().inflate(R.menu.main_pop_up_menu, popup.getMenu()); 

       popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { 
        public boolean onMenuItemClick(MenuItem item) { 


         if (item.getItemId() == R.id.pendingInvites) { 

          startActivity(new Intent(MainActivity.this, PendingInvitesActivity.class)); 

         } else if (item.getItemId() == R.id.feedback) { 
          final MaterialDialog dialog = new MaterialDialog.Builder(MainActivity.this) 
            .title("Feedback") 
            .customView(R.layout.feedback_dialog, true).build(); 

          positiveAction = dialog.getActionButton(DialogAction.POSITIVE); 

          edtName = (EditText) dialog.getCustomView().findViewById(R.id.editName); 
          edtEmailId = (EditText) dialog.getCustomView().findViewById(R.id.editTextEmailId); 
          edtComment = (EditText) dialog.getCustomView().findViewById(R.id.editTextComment); 
          buttonSave = (Button) dialog.getCustomView().findViewById(R.id.buttonSave); 

          buttonSave.setOnClickListener(new View.OnClickListener() { 
           @Override 
           public void onClick(View view) { 
            View view1 = getCurrentFocus(); 
            if (view1 != null) { 
             InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
             imm.hideSoftInputFromWindow(view1.getWindowToken(), 0); 
            } 
            mName = String.valueOf(edtName.getText().toString()); 

            mEmailId = String.valueOf(edtEmailId.getText().toString()); 

            mComment = String.valueOf(edtComment.getText().toString()); 

            if (mComment.equals("")) { 

             showAlert("Please enter comments."); 

            } else if (mEmailId.equals("")) { 

             showAlert("Please enter an email-id."); 

            } else { 

             if (!isValidEmail(mEmailId)) { 

              showAlert("Please enter valid email id."); 

             } else { 

              HashMap<String, String> params = new HashMap<String, String>(); 

              params.put("name", mName); 
              params.put("email_id", mEmailId); 
              params.put("comment", mComment); 

              CreateFeedbackAsyncTask createFeedbackAsyncTask = new CreateFeedbackAsyncTask(MainActivity.this, MainActivity.this); 
              createFeedbackAsyncTask.execute(params); 

              dialog.dismiss(); 

             } 
            } 

           } 
          }); 

          edtName.addTextChangedListener(new TextWatcher() { 
           @Override 
           public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
           } 

           @Override 
           public void onTextChanged(CharSequence s, int start, int before, int count) { 
            positiveAction.setEnabled(s.toString().trim().length() > 0); 


           } 

           @Override 
           public void afterTextChanged(Editable s) { 
            View view = getCurrentFocus(); 
            if (view != null) { 
             InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
             imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 
            } 
           } 
          }); 

          edtComment.addTextChangedListener(new TextWatcher() { 
           @Override 
           public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
           } 

           @Override 
           public void onTextChanged(CharSequence s, int start, int before, int count) { 
            positiveAction.setEnabled(s.toString().trim().length() > 0); 
            View view = getCurrentFocus(); 
            if (view != null) { 
             InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
             imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 
            } 

           } 

           @Override 
           public void afterTextChanged(Editable s) { 
           } 
          }); 

          edtEmailId.addTextChangedListener(new TextWatcher() { 
           @Override 
           public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
           } 

           @Override 
           public void onTextChanged(CharSequence s, int start, int before, int count) { 
            positiveAction.setEnabled(s.toString().trim().length() > 0); 
            View view = getCurrentFocus(); 
            if (view != null) { 
             InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
             imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 
            } 

           } 

           @Override 
           public void afterTextChanged(Editable s) { 
           } 
          }); 


          dialog.show(); 
          positiveAction.setEnabled(false); 

          return true; 
         } 

         return true; 
        } 

       }); 

       popup.show();//showing popup menu 
      } 
     }); 


     if (toolbar != null) { 
      toolbar.setTitle(""); 
      setSupportActionBar(toolbar); 

     } 

     if (toolbar != null) { 

      toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp); 
      toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        drawerLayout.openDrawer(GravityCompat.START); 

       } 
      }); 
     } 
    } 

    @Override 
    public void doPostExecute(JSONArray response) throws JSONException { 

     contactListArray = response; 

     contactDb = new ContactTableHelper(MainActivity.this); 

     if (null == contactList) { 
      contactList = new ArrayList<Contact>(); 
     } 

     for (int i = 0; i < contactListArray.length(); i++) { 
      JSONObject subObject1 = contactListArray.getJSONObject(i); 

      Contact contact = new Contact(); 
      JSONObject subObject = subObject1; 
      String contactName = subObject.getString("user_name"); 
      //name of the attribute in response 
      String pass = subObject.getString("password"); 
      String contactId = subObject.getString("user_id"); 
      String contactMobile = subObject.getString("mobile_no"); 
      String contactEmailId = subObject.getString("email_id"); 
      String contactProfile = subObject.getString("profile_image"); 
      String fullName = subObject.getString("full_name"); 
      String jobTitle = subObject.getString("job_title"); 
      String homeAddress = subObject.getString("home_address"); 
      String workPhone = subObject.getString("work_phone"); 
      String workAddress = subObject.getString("work_address"); 
      String company = subObject.getString("company"); 

      contact.setmThumbnail(contactProfile); 
      contact.setmUserName(contactName); 
      contact.setmMobileNo(contactMobile); 
      contact.setmEmailId(contactEmailId); 
      contact.setmProfileImage(contactProfile); 
      contact.setContactId(contactId); 
      contact.setmHomeAddress(homeAddress); 
      contact.setmFullName(fullName); 
      contact.setmJobTitle(jobTitle); 
      contact.setmWorkAddress(workAddress); 
      contact.setmWorkPhone(workPhone); 
      contact.setmPass(pass); 
      contact.setmCompany(company); 

      contactList.add(contact);//adding string to arraylist 

      contactDb.addContact(new Contact(contactId, contactName, pass, contactMobile, contactEmailId, contactProfile, fullName, jobTitle, workAddress, workPhone, homeAddress, company)); 

     } 

     adapter = new ContactAdapter(MainActivity.this, contactList); 
     recyclerView.setAdapter(adapter); 
     recyclerView.setHasFixedSize(true); 
     recyclerView.setItemViewCacheSize(20); 
     recyclerView.setDrawingCacheEnabled(true); 
     recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 

     contactList.clear(); 

     if (!firstTimeLogin) { 
      contactList.clear(); 
      contactList = contactDb.getAllContacts(); 
      mUser = mDb.getUser(mUserId); 

      txtuserName.setText(mUser.getmUserName()); 
      txtmobile.setText(mUser.getmMobileNo()); 
     } else { 
      new GetUserAsyncTask1(MainActivity.this,mUserId).execute(mUserId); 
      new GetContactsAsyncTask(this, MainActivity.this, mUserId, MainActivity.this).execute(); 

      firstTimeLogin = false; 

      SharedPreferences.Editor editor = getSharedPreferences("UserProfile", MODE_PRIVATE).edit(); 
      editor.putBoolean("login", firstTimeLogin); 
      editor.commit(); 
     } 

     recyclerView = (RecyclerView) findViewById(R.id.recycler_view); 

     recyclerView.setHasFixedSize(true); 
     RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(MainActivity.this); 
     recyclerView.setLayoutManager(mLayoutManager); 
     recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); 
     recyclerView.setItemAnimator(new DefaultItemAnimator()); 

     adapter = new ContactAdapter(MainActivity.this, contactList); 
     recyclerView.setAdapter(adapter); 

     recyclerView.addOnItemTouchListener(new RecyclerTouchListener(MainActivity.this, recyclerView, new ClickListener() { 
      @Override 
      public void onClick(View view, int position) { 
       final Contact contact = contactList.get(position); 

      } 

      @Override 
      public void onLongClick(View view, int position) { 

      } 
     })); 

    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
     switch (requestCode) { 
      case REQUEST_ID_MULTIPLE_PERMISSIONS: { 
       Map<String, Integer> perms = new HashMap<String, Integer>(); 

       perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED); 
       perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED); 
       perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED); 
       perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED); 

       for (int i = 0; i < permissions.length; i++) 
        perms.put(permissions[i], grantResults[i]); 

       if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED 
         && perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED 
         && perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED 
         && perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { 


       } else { 

        showAlert("Some Permissions are Denied."); 
       }  
      } 
      break; 
      default: 
       super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     } 
    } 

    @Override 
    public void doPostExecute(JSONObject response, Boolean update) throws JSONException { 


    } 
} 

主要佈局:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:id="@+id/drawer_layout" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<FrameLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/container"> 
</FrameLayout> 

<!-- Your normal content view --> 
<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:id = "@+id/toolbar_container"> 

    <!-- We use a Toolbar so that our drawer can be displayed 
     in front of the action bar --> 
    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:app="http://schemas.android.com/apk/res-auto" 
     android:id="@+id/main_toolbar" 
     android:layout_width="match_parent" 
     android:layout_height="?attr/actionBarSize" 
     android:background="?attr/colorPrimary" 
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
     app:popupTheme="@style/ThemeOverlay.AppCompat.Light"> 
     <RelativeLayout 
      android:layout_width="fill_parent" 
      android:layout_height="match_parent"> 
     <TextView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="@string/Contacts" 
      android:layout_gravity="center" 
      android:id="@+id/toolbar_title" 
      android:textSize="20sp" 
      android:textColor="#ffffff" 
      android:textStyle="bold" 
      android:textAlignment="center" 
      android:gravity="center_vertical|center|center_horizontal" 
      android:layout_toLeftOf="@+id/sync" 
      android:layout_toStartOf="@+id/sync" 
      android:layout_centerInParent="true" 
      android:layout_marginLeft="30dp" 
      android:layout_marginRight="10dp" /> 


     <ImageView 
      android:layout_width="24dp" 
      android:layout_height="24dp" 
      android:background="@drawable/ic_refresh_white_24dp" 
      android:id="@+id/sync" 
      android:layout_gravity = "right" 
      android:layout_toStartOf="@+id/menu" 
      android:layout_toLeftOf="@+id/menu" 
      android:layout_centerVertical="true" 
      android:layout_alignParentRight="false" 
      android:layout_marginRight="10dp" /> 

     <ImageView 
      android:layout_width="24dp" 
      android:layout_height="24dp" 
      android:layout_gravity= "end" 
      android:layout_marginRight="10dp" 
      android:background="@drawable/ic_more_vert_white_36dp" 
      android:id="@+id/menu" 
      android:layout_alignParentEnd="true" 
      android:layout_centerVertical="true" 
      android:layout_alignParentRight="true" /> 
     </RelativeLayout> 
    </android.support.v7.widget.Toolbar> 

    <view 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="#ffffff" 
     class="android.support.v7.widget.RecyclerView" 
     android:id="@+id/recycler_view" 
     android:layout_alignParentStart="true" 
     android:layout_alignParentLeft="true" /> 
    <!-- The rest of your content view --> 

</LinearLayout> 



<android.support.design.widget.NavigationView 
    android:id="@+id/navigation_view" 
    android:layout_width="wrap_content" 
    android:layout_height="match_parent" 
    android:layout_gravity="start" 
    android:background="?attr/colorPrimary" 
    app:headerLayout="@layout/drawer_header" 
    app:itemTextColor="@color/yourColor" 
    app:itemIconTint="@color/yourColor" 
    app:menu="@menu/nav_menu" > 
    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <include 
      layout="@layout/drawer_header" 
      android:layout_width="match_parent" 
      android:layout_height="103dp" /> 

     <ExpandableListView 

      android:id="@+id/elvGuideNavigation" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:groupIndicator="@null" 
      /> 

    </LinearLayout> 

</android.support.design.widget.NavigationView> 

+0

嘗試啓用/禁用hardwareaccelaration <應用軟件Android:硬件加速=「真」> – USKMobility

+0

你必須把你的'FrameLayout'裏面的'LinearLayout'和下面的' ToolBar'。因爲'DrawerLayout'只包含兩個主佈局。 – Ironman

+0

hardwareAcceleration沒有幫助.. @ USKMobility – Sid

回答

1

做JSON解析並添加條目進入DB也在後臺線程,並通過僅條目的ArrayList的主線程,這樣就可以減少對主線程的負載。

另一件事你可以嘗試在啓用hardwareAcceleration真

+0

hardwareAcceleration劑量沒有幫助.. – Sid

+0

我也嘗試創建一個片段,並將其替換爲主要活動的framelayout以分離代碼。但它仍然滯後。 – Sid

+0

即使你將代碼從主要活動中分離出來,並將其放在碎片中也不會有幫助。仍然有那些繁重的操作正在UI(主)線程中工作。您可以將解析邏輯和添加條目的數據添加到AsyncTask的doInBackground中的數據庫中,並且只將該列表傳遞給您的活動 –

1

勢必要移至另一個線程的任何數據庫操作。在onCreate()中解碼位圖也是很危險的。

也許組織你的代碼會有所幫助。

+0

我也嘗試創建一個片段,並將其替換爲主要活動的framelayout以分隔代碼。但它仍然滯後。 – Sid

+0

我嘗試評論所有位圖代碼仍然滯後。 – Sid

+0

是的,就像我說過的:除了位圖解碼之外,由於代碼的阻塞,數據庫操作仍然可能導致主線程丟幀。 –