findViewById returning null in fragment

后端 未结 2 1538
悲&欢浪女
悲&欢浪女 2020-12-17 22:48

I am replacing the existing fragment with new fragment and i am able to see my view but while setting on click listener on the button it returns null . I get the following e

相关标签:
2条回答
  • 2020-12-17 23:40
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle 
    
        savedInstanceState) {
                View view = inflater.inflate(R.layout.capture_card_phone_number, container, false);
                mPhone = (AutoCompleteTextView) getActivity().findViewById(R.id.phone_number);
                Button next = (Button) view.findViewById(R.id.capture_phone_next);
                next.setOnClickListener(this);
    
    
                return view;
    

    You have to call findViewById on your view - not on your activity.

    0 讨论(0)
  • 2020-12-17 23:46

    The reason is that in onCreateView the View of Fragment is not created yet, so it is returning null. Try to do it in onResume and it will return you the view:

    @Override
    public void onResume() {
        super.onResume();
        mPhone = (AutoCompleteTextView) getActivity().findViewById(R.id.phone_number);
        Button next = (Button) getActivity().findViewById(R.id.capture_phone_next);
        next.setOnClickListener(this);   
    }
    
    0 讨论(0)
提交回复
热议问题