解决fragment 的findViewByid为空 一个思路

在Activity的onCreate里添加Fragment,用findViewById给Fragment里的view添加点击事件会出现空指针,原因是Fragment的onCreateView未执行。解决办法是在Fragment里写接口回调,在Activity里实现接口添加findViewById,适合动态添加布局,一般情况推荐在Fragment的onCreateView中写逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

activity  add Fragment一般都是在oncreate里面做 然后   想给fragment 里面的view添加点击事件  用findViewById 会出现空指针

这是因为虽然你把fragment add到Activity里了,但是 Fragment的oncreateView没执行,所以拿不到他的view

 

我的办法是再Fragment里面写个接口回调,然后 在activity里面实现这个接口  加入想要的findViewById

//fragment中定义接口 ,这个View传入fragment的布局View
public interface   AfterOnCreateView{
        void afterOncreateView(View view);
    }
    public  AfterOnCreateView afterOnCreateView;




然后在onCreateView中加入这个接口回调


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, 
     @Nullable Bundle savedInstanceState) {
    View   view = inflater.inflate(R.layout.fragment_capture, null);
        if(afterOnCreateView!=null){
            afterOnCreateView.afterOncreateView(view);
        }
return  view
}

最后在Activity的oncreate方法中实现这个接口

 captureFragment.afterOnCreateView= new CaptureFragment.AfterOnCreateView(){
            @Override
            public void afterOncreateView(View view) {

//....fragment的View逻辑
}
}

这种方式适合 动态添加fragment布局的情况,这样ui的逻辑就需要写在activity里面,如果一般时候,就推荐在Fragment的onCreateView中写逻辑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值