自动生成文档
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 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
动态创建 以及add,remove,replace,hide 方法
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//碎片管理器
FragmentManager supportFragmentManager = getSupportFragmentManager();
//开启事务
FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
FristFragment fristFragment = new FristFragment();
fragmentTransaction.add(R.id.layout_content,fristFragment);
//替换的方法
// fragmentTransaction.replace(R.id.layout_content,new BlankFragment());
//移除
// fragmentTransaction.remove(fristFragment);
//显示
// fragmentTransaction.show(fristFragment);
//隐藏
fragmentTransaction.hide(fristFragment);
//提交事务
fragmentTransaction.commit();
}
}