如何在导航抽屉中保存片段状态?

时间:2014-08-16 08:00:29

标签: android android-fragments navigation-drawer

我在我的Android应用程序中使用导航抽屉,当我重新选择片段时,它会加载两次 这是我的代码

    private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
    case 0:
        // if(fraghome!=0)
        // {
        // fraghome=0;
        fragment = new HomeFragment();
        // }
        break;
    case 1:
        fragment = new BlogsFragment();
        break;
    case 2:
        fragment = new NewsFragment();
        break;
    case 3:
        fragment = new TransferFragment();
        break;
    case 4:
        fragment = new FixturesFragment();
        break;
    // case 5:
    // fragment = new BestXIFragment();

    // break;
    case 5:
        fragment = new FeedFragment();
        break;
    case 6:
        fragment = new TwitterFragment();
        break;
    case 7:
        fragment = new FacebookFragment();
        break;
    case 8:
        fragment = new BookmarkFragment();
        break;
    default:
        break;
    }

    if (fragment != null) {

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.replace(R.id.frame_container, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }
}

在每个片段中我使用异步任务,当我选择片段时,异步任务一次又一次地启动 请帮帮我

1 个答案:

答案 0 :(得分:0)

通常在片段中,如果碎片不是当前顶部片段或片段恰好在当前顶部片段的右侧或左侧,则会破坏碎片。因此asynctask被一次又一次地调用。 我假设您使用asynctask获取一些数据以显示在片段中。因此,在执行asynctask之前,尝试使数据源变量为static并检查数据源变量的null。如果数据源不为null,则显示数据。我已经添加了一些abstruct代码供您理解。为了更好地理解,你可以看到this link.希望它有所帮助。感谢.....

在每个片段中......

public class TabFragment extends Fragment{
    private static DataSource ds = null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /*
        .
        other view initializing work
        .
        */
        if(ds == null){
            //execute asynctask and set data to ds in asynctask
        } else {
            // set data to view.
        }
        return view;
    }
}