Fragment与Activity通信

246 阅读1分钟

theme: channing-cyan

Fragment动态添加与管理

frament自带有一个管理器FragmentManager负责管理页面中的每一个碎片。fragment的切换首先要获得FragmentManager,然后通过FragmentTransaction()方法进行操作

  • [创建一个待处理的fragment]
  • [通过getSupportFragmentManager()方法获取fragManager]
  • [调用fragmentManager的beginTransaction()方法开启一个事务transaction]
  • [使用transaction进行fragment的切换]
  • [提交事务]
private void replaceFragment(Fragment fragment) {
    FragmentManager fragmentManager =getSupportFragmentManager();
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fraglayout,fragment);
    //放入一个栈中  返回操作
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

addToBackStack()方法在每一次切换Fragment的时候将其压入工作栈中,通过触发返回键可以到达上一级页面。

Activity与Fragment通信的方案

Bundle类

Fragment与Activity之间的通信要通过Bundle类来执行,通过Bundle类的put方法将参数传递给相应的fragment。

Bundle bundle=new Bundle();
bundle.putString("msg","i like china");
BlankFragment bf=new BlankFragment();
bf.setArguments(bundle);
replaceFragment(bf);

在fragment中获取这个信息的时候只需要再声明一个Bundle类,通过其get方法即可得到传入的参数。

Bundle bundle=this.getArguments();
String string=bundle.getString("msg");

java面向接口

eventBus、LiveData(第三方库)