fragment.onCreateView causes null pointer exception

前端 未结 3 455
小蘑菇
小蘑菇 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().

提交回复
热议问题