一、Fragment生命周期:
二、动态添加Fragment的三步:
1、获得Fragment的管理者FragmentManager
FragmentManager fragmentManager = getFragmentManager();
2、开启事务:
FragmentTransaction transaction = fragmentManager.beginTransaction();
3、提交事务:
transaction.commit();
下面是四个Fragment的切换:
public void onClick(View view) { //获得fragment的管理者 android.app.FragmentManager fragmentManager = getFragmentManager(); //开启事物 FragmentTransaction transaction = fragmentManager.beginTransaction(); switch (view.getId()){ case R.id.btn_wx:{//点击类微信 transaction.replace(R.id.ll,new WxFragment()); }break; case R.id.btn_contact:{//点击了联系人 transaction.replace(R.id.ll,new ContactFragment()); }break; case R.id.btn_discover:{//点击了发现 transaction.replace(R.id.ll,new DiscoverFragment()); }break; case R.id.btn_me:{//点击了me transaction.replace(R.id.ll,new MeFragment()); }break; default: break; } //最后一步,提交事物 transaction.commit(); }
以WxFragment为例:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //通过打气筒把一个布局转换成一个view对象 View view = inflater.inflate(R.layout.fragment_wx,null); return view; }
三、Fragment之间的通信:
已Fragment1修改Fragment2的TextView的值为例:
MainActivity:
android.app.FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.ll1,new Fragment1(),"f1"); transaction.replace(R.id.ll2,new Fragment2(),"f2"); transaction.commit();
Fragment1:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment1,null); view.findViewById(R.id.bnt).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //修改TextView的值 Fragment2 f2 = (Fragment2)getActivity().getFragmentManager().findFragmentByTag("f2");
//调Fragment2中的setText函数修改TextView的值 f2.setText("haha"); } }); return view; }
Fragment2:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment2,null); tv = (TextView) view.findViewById(R.id.tv); return view; } public void setText(String content){ tv.setText(content); }
ps:通过Tag可以得到Fragment2的实例,然后去修改值就行了。