Android开发时Fragmen页面不能使用findViewById()获取控件

最近有在学习Android引用开发

平台是:Android stdio

SDK:Android 10、API 29

 

废话开始了!!!!

 

为了实现底部导航菜单栏的功能,增加了Fragment。在定义好的Fragment页面中有<Button>控件定义在xml文档中,在定义页面类文件为其实现功能时,发现不能使用findViewById()方法来获取控件。

原来Fragment页面默认继承的是Fragment类,并没有实例化页面为Activity。而findViewById()方法是Activity实例独有的获取控件的方法。

 

解决方法:

通过getActivity()方法。以下是getActivity()的函数定义:可知getActivity()方法返回的是一个FragmentActivity对象。

/**
     * Return the {@link FragmentActivity} this fragment is currently associated with.
     * May return {@code null} if the fragment is associated with a {@link Context}
     * instead.
     *
     * @see #requireActivity()
     */
    @Nullable
    final public FragmentActivity getActivity() {
        return mHost == null ? null : (FragmentActivity) mHost.getActivity();
    }

于是我试过使用getActivity()方法来

结果报错来了:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myschool10, PID: 14418
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

原来是在onCreateView()方法中不能使用setOnClickListener()的事件监听

必须换在onActivityCreated()方法中使用

完整版代码:

public class PushFragment extends Fragment {
    private Button addphoto;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.push_fragment,container,false);
        return view;
    }
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button button =getActivity().findViewById(R.id.click_to_push);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("success");
            }
        });
        
    }
}

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值