我会制作一个包装片段,它知道要显示什么 - 列表或详细信息。这将与ViewPager
- pager 只知道它包含包装片段完全分离,并且这些片段将自己管理它们的内容。
实施将遵循以下原则:
public class WrapperFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyListFragment list = new MyListFragment();
list.setListAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> l, View v, int position, long id) {
// Create details fragment based on clicked item's position
Fragment details = new Fragment();
getChildFragmentManager()
.beginTransaction()
.replace(R.id.container, details)
.addToBackStack(null)
.commit();
}
});
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, list)
.commit();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// There has to be a view with id `container` inside `wrapper.xml`
return inflater.inflate(R.layout.wrapper, container, false);
}
public class MyListFragment extends ListFragment {
private OnItemClickListener listener;
public void setOnItemClickListener(OnItemClickListener l) {
this.listener = l;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if(listener != null) {
listener.onItemClick(l, v, position, id);
}
}
}
}
wrapper.xml
. 想法是WrapperFragment
必须提供一个布局,其中包含一个带有 id 的视图container
- 因为我们正在使用带有这个 id 的视图来放置子片段 -MyListFragment
或DetailsFragment
.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
其他方式。这应该可行,但您必须尝试一下(布局id
本身,而不是有一个 id 的孩子container
):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>