首先创建Fragment的代码
代码下图实例
public class MyFragment extends Fragment {
public MyFragment() {
// Required empty public constructor
}
/**
* 参数详解
* fragment第一次创建用户界面时回调的方法
* @param inflater 实体加载器,用于加载一个fragment的视图
* @param container 表示当前fragment插入到activity中的对象
* @param savedInstanceState 表示储存一个fragment的信息
* @return
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my, container, false);
}
}
xml布局代码如下:
<?xml version="1.0" encoding="utf-8"?>
<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=".fragment.MyFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
代码的核心要有标签
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--一定要注意的是:name属性是fragment的全限定名-->
<fragment
android:id="@+id/my_fragment_id"
android:name="com.example.day004.fragment.MyFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</fragment>
</LinearLayout>
Fragment常用的方法
添加Fragment的方法:add()
替换Fragment的方法:replace()
移除Fragment的方法:remove()
隐藏/显示Fragment的方法:hide()/show()
add添加方式:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
FragmentA fragmentA=new FragmentA();
transaction.add(R.id.main_frame_layout, fragmentA);
transaction .hide(fragmentB);
transaction.show(fragmentA);
1:获得FragmentManager对象
FragmentManager fragmentManager=getFragmentManager();
2:开启事务
FragmentTransaction transaction = fragmentManager.beginTransaction();
3:通过FragmentTransaction 调用add()、replace()方法管理fragment
4:transaction .commit();