1.动态加载Fragment的核心代码四步走
//1.拿到碎片管理器 FragmentManager fragmentManager = getFragmentManager(); //2.开启事务 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); //3.执行事务(★) fragmentTransaction.replace(R.id.fragment_layout, new WeixinFragment()); //4.事务提交 fragmentTransaction.commit();
四个步骤里面最重要的莫过于第三步执行事务。
执行事务包括添加、替换、移除碎片。但是这里非常不建议用add来添加碎片,而是建议用替换的方式来添加碎片,以防出现碎片重叠的情况。
第三步的两个参数非常重要,第一个参数是我们自定义的碎片布局,它是一个LinearLayout/RelativeLayout...布局;
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/weixin_tv" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="通讯录" android:textSize="50sp" /> </LinearLayout>
第二参数是自定义的Fragment对象,它继承自Fragment。
public class ContactFragment extends Fragment{ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_contact, null); return view; } }
在它的onCreateView方法里面我们可以用打气筒来加载它。注意!碎片的加载一定不是在MainActivity里面用打气筒加载!
本文不在此讨论静态添加碎片的方法,因为实在是不常用。。。
2.碎片开启活动
public class LeftFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.left_fragment, null); Button start_bnt = view.findViewById(R.id.start_bnt); //设置按钮点击事件 start_bnt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = getActivity();//★ Intent intent = new Intent(activity.getApplicationContext(), MainActivity.class); startActivity(intent); } }); return view; } }
只要有getActivity()这行代码,剩下的就是常规操作了。
3.碎片开启碎片
public class LeftFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.left_fragment, null); Button start_bnt = view.findViewById(R.id.start_bnt); //设置按钮点击事件 start_bnt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = getActivity(); FragmentManager fragmentManager = activity.getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.ll_right,new RightFragment()); fragmentTransaction.commit(); } }); return view; } }
碎片不能直接开启碎片,必须通过Activity作为桥梁。
同样,只要有getActivity()这行代码,剩下的就是常规操作了。