fragment.onCreateView causes null pointer exception

前端 未结 3 427
小蘑菇
小蘑菇 2021-01-13 19:41

So i am using fragments and trying to wire on click listeners on them.

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bun         


        
相关标签:
3条回答
  • 2021-01-13 20:17

    You cannot use getView() until onCreateView() returns since it is the method in charge of creating said view. You should change your code to

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View contentView = inflater.inflate(R.layout.layout1, null);
            startButton = (Button) contentView.findViewById(R.id.button);
    

    Or alternatively, override onViewCreated() and implement your Button setup in that method (using getView().

    0 讨论(0)
  • 2021-01-13 20:22

    This line makes no sense:

    startButton= (Button) getView().findViewById(R.id.button);
    

    You don't have a View yet, you are still creating it..

    In stead you can do this:

     startButton= (Button)contentView.findViewById(R.id.button);
    

    Or wait until the onCreateView method returns the actual View you just created and then you will be able to get a reference of the view using the "getView" method after onCreateView returns the view..

    Hope it Helps!

    Regards!

    0 讨论(0)
  • 2021-01-13 20:23

    simply use this in your onCreateView

        View contentView = inflater.inflate(R.layout.layout1, container, false);
        startButton= (Button) contentView.findViewById(R.id.button);
        return contentView;
    
    0 讨论(0)
提交回复
热议问题