我正在尝试将多个片段添加到LinearLayout。
容器代码
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
inflater.inflate(R.layout.fragment_container, container, false);
View rootView=inflater.inflate(R.layout.fragment_container, container, false);
LinearLayout linearLayout = (LinearLayout) rootView.findViewById(R.id.LinLay);
linearLayout.addView(MyFragment.newInstance("Params", "Random"),0);
return rootView;
}
容器的XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nt.projet.ToDoList">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:id="@+id/LinLay"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:animateLayoutChanges="true"
android:layout_gravity="center"
android:nestedScrollingEnabled="true"
android:showDividers="end"
android:translationZ="5dp"></LinearLayout>
</FrameLayout>
片段代码
public static MyFragment newInstance(String param1, String param2) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
inflater.inflate(R.layout.fragment_high_priority_task, container, false);
View rootView = inflater.inflate(R.layout.fragment_high_priority_task, container, false);
return rootView;
}
我将向我将在Fragment中创建的按钮添加一些onClickListeners。我想以编程方式向布局添加无限数量的片段。我该怎么做呢?
答案 0 :(得分:0)
您无法添加View(),然后传入片段的新实例。这是错的:
linearLayout.addView(MyFragment.newInstance("Params", "Random"),0);
并将newInstance(...)
更改为:
MyFragment fragment = new MyFragment();
然后使用FragmentTransaction
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (mCurrentFragment != null) {
mCurrentFragment = NewFragment.newInstance("Your Argument");
}
ft.add(R.id.LinLay, mCurrentFragment,);
ft.commit();
如果您使用的是Activity而不是FragmentAcitivity,则需要使用getFragmentManager()
代替getSupportFragmentManager()