【问题标题】:right way to make fragment transacrtion进行片段交易的正确方法
【发布时间】:2014-12-03 13:20:33
【问题描述】:

我正在开发具有一个活动和多个片段的 android 应用程序。我的应用程序包含导航抽屉。它的布局包含列表视图。单击它的项目,我使用ft.replace(R.id.my_placehodler, new MyFragment()) 动态更改片段并将事务添加到backstack ft.addToBackstack(null)。当我每次实例化新片段时进行新事务时。在我看来,这不是一个好方法。你能给我一些关于进行片段交易的正确方法的建议吗?

【问题讨论】:

  • 你看过 FragmentManager 在片段之间切换吗?
  • 不,我没有。你的意思是我应该跟踪片段管理器中的片段数量吗?

标签: android android-fragments fragmenttransaction fragment-backstack


【解决方案1】:

只需调用setFragment(FragmentClassObject,false,"fragment"); 方法。

public void setFragment(Fragment fragment, boolean backStack, String tag) {
    manager = getSupportFragmentManager();
    fragmentTransaction = manager.beginTransaction();
    if (backStack) {
        fragmentTransaction.addToBackStack(tag);
    }
    fragmentTransaction.replace(R.id.content_frame, fragment, tag);
    fragmentTransaction.commit();
}

【讨论】:

    【解决方案2】:

    如果您想避免为同一类 Fragment 实例化多个实例,即您希望每个 Fragment 类有一个实例,则可以使用标签来识别每个 Fragment。

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        String tag = "";
        switch (position) {
        case 0:
            tag = "fragment_0";
            break;
        case 1:
            tag = "fragment_1";
            break;
        case 2:
            tag = "fragment_2";
            break;
        }
    
        FragmentManager fragmentManager = getFragmentManager();
        Fragment fragment = fragmentManager.findFragmentByTag(tag);
        if (fragment == null) {
            // Only in case there is no already instaciated one,
            // a new instance will be instanciated.
            switch (position) {
            case 0:
                fragment = new Fragment_class_0();
                break;
            case 1:
                fragment = new Fragment_class_1();
                break;
            case 2:
                fragment = new Fragment_class_2();
                break;
            }
        }
    
        fragmentManager.beginTransaction().replace(R.id.container, fragment, tag).commit();
    }
    

    【讨论】:

    • 正如我从您的回复中得到的那样,如果它已经实例化,我必须将标签设置为片段以便从片段管理器中获取它。我说的对吗?
    • 不只是设置。首先,为同一类设置标签(例如,“fragment_0”为 Fragment_Class_1,“fragment_1”为 Fragment_Class_2,等等)。其次,找到一个已经实例化的片段对象(如果存在)(findFragmentByTag)。如果没有已经实例化的对象,则将实例化该类的新对象。
    猜你喜欢
    • 2017-03-13
    • 1970-01-01
    • 2014-11-06
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多