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

后端 未结 3 1238
时光取名叫无心
时光取名叫无心 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 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;
    }
    

提交回复
热议问题