8

我已经实现了一个导航抽屉,我想在导航抽屉关闭之前加载我的片段。目前,片段与抽屉关闭并行加载,因此如果片段很重,用户界面会挂起一段时间。

我的代码是:

private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
                 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                 ft.replace(R.id.content_frame, fragmentProfile);
                 ft.commit();
                 drawerLayout.closeDrawer(drawerNaviListView);
        }
    }

我怎样才能改变它,以便我首先看到我的片段加载(在后台),当它完成加载时,导航抽屉关闭?

4

3 回答 3

3

Try to load after the drawer is closed Use handler to create a delayed execution. So that there won't be any hang when the drawer closes

Inside the method onItemClick(), use the below code :

Handler handler = new Handler();

Runnable runnable = new Runnable() {

            @Override
            public void run() {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
             ft.replace(R.id.content_frame, fragmentProfile);
             ft.commit();

            }
        };

        handler.postDelayed(runnable, 500); // here 500 is the delay 

// other way of doing it is

create an AsyncTask and in doInBackground() method start the fragment transaction and close the drawer in onPostExecute()

于 2014-06-20T09:31:02.073 回答
3

我的解决方案是在抽屉关闭后加载片段:实际上在 onDrawerClosed 内部调用 loadFragment 方法

 public void onDrawerClosed() {

 // assure the request comes from selecting a menu item, not just closing tab
 if (selectedTab ) 
     selectItem(mSelectedFragment);
     selectedTab = false;
 }
于 2014-01-31T17:18:06.833 回答
2

DrawerLayout.DrawerListener 可用于监视抽屉视图的状态和运动。 避免在动画过程中执行昂贵的操作,例如布局,因为它会导致卡顿;尝试在 STATE_IDLE 状态期间执行昂贵的操作。来源

换句话说,Android 建议您在交换 Fragments 之前等待抽屉关闭。

于 2013-11-19T22:39:31.993 回答