Button button = findViewById(R.id.button) always resolves to null in Android Studio

后端 未结 3 1239
时光取名叫无心
时光取名叫无心 2020-12-13 16:18

I\'m new to Android development and Android Studio, so pardon my ignorance.

findViewById of a button I added always resolves to null. Henc

相关标签:
3条回答
  • 2020-12-13 16:59

    R.id.button is not part of R.layout.activity_main. How should the activity find it in the content view?

    The layout that contains the button is displayed by the Fragment, so you have to get the Button there, in the Fragment.

    0 讨论(0)
  • 2020-12-13 17:01

    The button code should be moved to the PlaceholderFragment() class. There you will call the layout fragment_main.xml in the onCreateView method. Like so

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        Button buttonClick = (Button) view.findViewById(R.id.button);
        buttonClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onButtonClick((Button) view);
            }
    
        });
    
        return view;
    }
    
    0 讨论(0)
  • 2020-12-13 17:13

    This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

    Move that piece of code in the onCreateView() method of the fragment:

    //...
    
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    Button buttonClick = (Button)rootView.findViewById(R.id.button);
    buttonClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onButtonClick((Button) view);
        }
    });
    

    Notice that now you access it through rootView view:

    Button buttonClick = (Button)rootView.findViewById(R.id.button);
    

    otherwise you would get again NullPointerException.

    0 讨论(0)
提交回复
热议问题