传递继承Fragment的自定义Fragment类特定参数

继承Fragment的自定义Fragment类CustomFragment,不能像继承Activity的自定义Activity类CustomActivity一样,通过修改构造方法来实现传递参数。所以我们要通过bundle和instance来实现。 分四步: 1.创建参数对应的全局变量,用于使用。 2.newInstance初始化Fragment,通过方法里传递参数和Bundle。 3.将初始化Fragment时用Bundle传入的参数,赋值给全局变量。 4.当我需要用到对应参数数据时,可以通过调用对应参数的全局变量来使用。

public class CustomFragmentextends Fragment {
//1.创建参数对应的全局变量,用于使用
    @LayoutRes
    private int sampleLayoutRes;
    @LayoutRes
    private int practiceLayoutRes;

//2.newInstance初始化Fragment,通过方法里传递参数和Bundle。
    public static  CustomFragment newInstance(@LayoutRes int sampleLayoutRes,@LayoutRes int practiceLayoutRes){
        CustomFragment fragment = new CustomFragment();
        Bundle args = new Bundle();
        args.putInt("sampleLayoutRes",sampleLayoutRes);
        args.putInt("practiceLayoutRes",practiceLayoutRes);
        fragment.setArguments(args);
        return  fragment;
    }

//3.将初始化Fragment时用Bundle传入的参数,赋值给全局变量。
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if(null != args){
            sampleLayoutRes = args.getInt("sampleLayoutRes");
            practiceLayoutRes = args.getInt("practiceLayoutRes");
        }
    }

//4.当我需要用到对应参数数据时,可以通过调用对应参数的全局变量来使用。
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fragment_page,container,false);

        ViewStub sampleStub = (ViewStub) view.findViewById(R.id.sampleStub);
        sampleStub.setLayoutResource(sampleLayoutRes);
        sampleStub.inflate();

        ViewStub practiceStub = (ViewStub) view.findViewById(R.id.practiceStub);
        practiceStub.setLayoutResource(practiceLayoutRes);
        practiceStub.inflate();
        return view;
    }
}
复制代码

在activity里调用CustomFragment 时,就可以创建CustomFragment 对象时传递参数了。

PageFragment.newInstance(R.layout.sample_color, R.layout.practice_color)
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值