【发布时间】:2012-03-24 22:41:39
【问题描述】:
我正在尝试在 Android 中学习 Fragments,从各种示例中我发现似乎有不同的方法,我只是想就哪种方法正确,或者至少在哪种情况下获得一些建议应该使用另一种方式。
一个示例创建了一个包含片段和 FrameLayout 的布局。在代码中,当从 ListFragment 中选择一个项目时,会创建一个新的 Fragment(在构造函数中需要一些数据)并将 FrameLayout 替换为这个新的 Fragment(使用 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);
}
}
【问题讨论】:
标签: android android-layout android-fragments