Android Fragments应该重用1个片段还是创建新实例?

时间:2012-03-24 13:23:58

标签: android android-layout android-fragments

我正在尝试学习Android中的碎片,并且从各种示例中我发现似乎有不同的方法,我只是想得到一些关于哪种方法是正确的建议,或者至少在哪种情况下方式应该用在另一个方面。

一个示例创建了一个包含片段和FrameLayout的布局。在代码中,当从ListFragment中选择一个项目时,会创建一个新的Fragment(在构造函数中需要一些数据),并使用这个新的Fragment替换FrameLayout(使用FragmentTransaction.replace())。

另一个例子有一个布局文件,它并排声明了2个片段。现在在代码中,当用户从一个片段中的列表中选择一个项目时,将调用另一个片段来更新数据(基于所选项目)。

所以我只是想知道这些方法中的任何一种是否比其他方法更受欢迎,或者是否存在应该使用某种方法的情况?

编辑:这是我所指的两种方法中的每一种的代码:

1:

        mCurCheckPosition = index;

        if (mDualPane) {
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.
            getListView().setItemChecked(index, true);

            // Check what fragment is currently shown, replace if needed.
            DetailsFragment details = (DetailsFragment)
                    getFragmentManager().findFragmentById(R.id.details);
            if (details == null || details.getShownIndex() != index) {
                // Make new fragment to show this selection.
                details = DetailsFragment.newInstance(index);

                // Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.details, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } else {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), DetailsActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);
        }

2:

public void onListItemClick(ListView l, View v, int position, long id) {
    String item = (String) getListAdapter().getItem(position);
    DetailFragment fragment = (DetailFragment) getFragmentManager()
            .findFragmentById(R.id.detailFragment);
    if (fragment != null && fragment.isInLayout()) {
        fragment.setText(item);
    } else {
        Intent intent = new Intent(getActivity().getApplicationContext(),
                DetailActivity.class);
        intent.putExtra("value", item);
        startActivity(intent);

    }

}

1 个答案:

答案 0 :(得分:20)

  

所以我只是想知道这些方法中的任何一种是否比其他方法更受欢迎,或者是否存在应该使用某种方法的情况?

如果实际片段不需要改变(即,它是相同的片段类),我会让活动在该片段上调用一个方法而不是替换它(你的场景#2),假设它存在。这在运行时要便宜得多,而且编码也可能更简单。

但是,如果片段可能需要不同(例如,取决于您单击的内容,列表中表示的不同类型的模型对象可能存在不同的片段),则需要替换片段(你的场景#1)。您可以优化片段发生的情况,因为此事件属于同一类,但我首先关注的是通过替换片段使其工作,并担心如果/当您有时间和倾向。

不过,我不是你的#2代码的粉丝。恕我直言,片段不应该直接与其他片段交谈。我喜欢的模式是片段“坚持编织”,专注于他们自己的小部件和模型中的事物。对于影响UI的其他部分的事件(例如,列表单击),让片段通知活动(例如,通过监听器接口)。活动是知道应该在哪些片段周围的活动,因为它是首先创建它们的活动。然后,活动可以与另一个片段(如果存在)进行通信,创建另一个片段(如果有空间),或者启动另一个活动。如果你更喜欢你的#2方法,欢迎你使用它 - 这不是我在你的环境中所做的。