函数:
public abstract FragmentTransaction add(int containerViewId, Fragment fragment);
getFragmentManager().beginTransaction().add(R.id.frgmt_top, new TopFrgmt()).commit()
作用:
add 是把一个fragment添加到一个容器 container 里。并且显示container的内容+fragment对应的view的内容.
注意:
R.id.frgmt_top必需在执行add时所在的layout中.
示例1:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MActivity" tools:ignore="MergeRootFrame" > </FrameLayout>
public class MActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.container, new MainFrgmt()).commit(); } } }
R.id.container必需在 R.layout.activity_main 中
示例2:
frgmt_main.xml中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" ... > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > ... </LinearLayout> <LinearLayout android:id="@+id/frgmt_top" android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginTop="18dp" android:gravity="center_horizontal" android:background="#ff09a23d" android:orientation="horizontal" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="top" /> </LinearLayout>
</LinearLayout>
MainFrgmt.java中
public class MainFrgmt extends Fragment implements OnClickListener { private LinearLayout top, center, bottom; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.frgmt_main, container, false); ...return rootView; } @Override public void onClick(View v) { FragmentManager fmgr = getFragmentManager(); FragmentTransaction ft = fmgr.beginTransaction(); switch (v.getId()) { case R.id.tog_top: if (tog_top.isChecked()) { ft.add(R.id.frgmt_top, new TopFrgmt()); } else { Fragment frmg = fmgr.findFragmentById(R.id.frgmt_top); ft.remove(frmg); } break; //...
R.id.frgmt_top必需在frgmt_main.xml中
时间: 2024-12-09 17:59:54