首先你需要一个布局
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
然后jiava调用
// Create a new Fragment to be placed in the activity layout
HeadlinesFragment firstFragment = new HeadlinesFragment();
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
这里控制fragment主要是FragmentManager和FragmentTransaction。
// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
addToBackStack(null) 执行事务时,能让用户能够回退并“撤消”更改。
replace() 替换方法
fragment有两个分别是android.app.Fragment和 android.support.v4.app.Fragment,用的时候需要注意是继承哪个类。xml里面要改,java文件里面的也要改。xml文件里面大写字母开头的FrameLayout表示android.support.v4.app.Fragment,小写的字母开头的fragment表示android.app.Fragment的。getSupportFragmentManager()是android.support.v4.app.Fragment里面的方法。
相关资料
1.官网资料