我正在尝试构建一个三窗格布局(三个ListFragment
)。我可以通过以下布局在活动中创建它
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Fragment android:name="com.example.android.fragments.HeadlinesFragment"
android:id="@+id/category_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<Fragment android:name="com.example.android.fragments.HeadlinesFragment2"
android:id="@+id/sub_category_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<Fragment android:name="com.example.android.fragments.HeadlinesFragment3"
android:id="@+id/sub_sub_category_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
但是我nested fragment
在嵌套片段中使用和,必须动态添加片段,FrameLayout
这就是我编写这些代码的原因:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/category_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<FrameLayout
android:id="@+id/sub_category_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<FrameLayout
android:id="@+id/sub_sub_category_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
但它不起作用。我怎样才能做到这一点?
编辑:
public class CompetitiveProgramming extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.competitive_programming_exercise, container, false);
Fragment a = new HeadlinesFragment();
Fragment b = new HeadlinesFragment2();
Fragment c = new HeadlinesFragment3();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.category_fragment, a );
transaction.add(R.id.sub_category_fragment, b );
transaction.add(R.id.sub_sub_category_fragment, c );
transaction.commit();
return rootView;
}
@Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
三个片段是这样的:
public class HeadlinesFragment extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView=new TextView(getActivity());
textView.setText("Hello I am fragment C");
return textView;
}
}