- I created a new project with empty activity selected.
- Then I added a new layout file called
layout_extra.xml
withid
oflayout_extra
and it just contains one switch withid
ofswitch1
. - The
activity_main.xml
contains a button withid
ofbutton
to navigate to thelayout_extra
. - The content of
MainActivity.java
is as follows:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(v->{
setContentView(R.layout.layout_extra);
});
findViewById(R.id.switch1).setOnClickListener(v->{
findViewById(R.layout.layout_extra).setBackgroundColor(Color.RED);
});
}
}
Question
I got the following error on the Android Studio.
The tooltip gives the following info.
I did all the given suggestions but none works (the application crashes).
How to properly call resource id from within an anonymous class method?
3
Answers
The setOnClickListener() use a new view so
findViewById(R.layout.layout_extra).setBackgroundColor(Color.RED);
didn’t work, you should try :Hum, the method "findViewById()" is asking the ID of the Object not the Resource.
Basically what i believe you should do is set the "ID" in the "XML" of your main layout, than you can use the method "findViewById()", any object has an id in "XML" even the layout can be set an ID.
Ex:
Set in the XML the id of you main object:
in the code:
I think I have got the error. You are calling
setOnClickListener()
on a null object. Hence, the updated code should be:where
R.id.layout_extra
refers to theid
of the root element oflayout_extra.xml
.