Fragment小记
1、创建Fragment
- 先创建fragment的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/left">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text"
android:text="hello"/>
</LinearLayout>
- 创建一个Fragment1类继承自Fragment,重写onCreateView方法,加载布局文件
public class Fragment1 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1, container, false);//设为false否则会报错,至于为什么,以后再深究
return view;
}
}
2、将fragment添加到MainActivity中
- 在MainActivity的布局文件中增加FrameLayout,用来显示fragment
<FrameLayout
android:layout_width="match_parent"
android:layout_height="500dp"
android:id="@+id/layout"
/>
- 将fragment动态添加到MainActivity中,不要直接在布局文件中引用!
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.layout, new Fragment1());
fragmentTransaction.commit();
3、点击按钮进行fragment的切换
View.OnClickListener l = new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Fragment f = null;
switch(view.getId()) {
case R.id.btn1:
f = new Fragment1();
break;
case R.id.btn2:
f = new Fragment2();
break;
default: break;
}
fragmentTransaction.replace(R.id.layout, f);
fragmentTransaction.commit();
}
};