Activity和Fragment 互相传值

                                                                      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

 

  1. 定义接口、设置值
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();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值