I\'m new to Android development and Android Studio, so pardon my ignorance.
findViewById
of a button I added always resolves to null
. Henc
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.
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;
}
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.