Activity和Fragment 互相传值
一、Activity向Fragment传值
应用例子:在Activity中,请求后台数据。通过RecyclerView切换Fragment页面,传递到Fragment中。
Activity 通过getInstance传值。
private void setLightFragment() {
if (lightFragment == null) {
lightFragment = LightFragment.getInstance(status);
getSupportFragmentManager().beginTransaction().add(R.id.lay_frame_device, lightFragment).commit();
}
getSupportFragmentManager().beginTransaction().show(lightFragment).commit();
}
Fragment 通过Bundle接收。
public static LightFragment getInstance(int status) {
LightFragment lightFragment = new LightFragment();
Bundle bundle = new Bundle();
bundle.putInt("status", status);
mStatus = status;
lightFragment.setArguments(bundle);
return lightFragment;
}
- 二、Fragment改变进入它之前,更新Activity页面中adapter、标题等值
Fragment
- 定义接口、设置值
public RenameListenerImp renameListenerImp;
public interface RenameListenerImp {
void setRename(String newName);
}
renameListenerImp.setRename(renameStr);
2、在onAttach处理
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof RenameListenerImp) {
renameListenerImp = (RenameListenerImp) context;
} else {
throw new RuntimeException(context.toString() +
" must implement OnFragmentInteractionListener");
}
}
Activity 实现接口 设置新标题、刷新adapter
implements CabinetDoorFragment.RenameListenerImp
@Override
public void setRename(String newName) {
setTitle(newName);
subdevicesList.get(0).setName(newName);
adapter.notifyDataSetChanged();
}