I have an app that is setting the contentView when images are clicked.This one from my main.xml loads the options.xml fine.
settings.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
setContentView(R.layout.options);
}
});
But when I add a listener to an image that is inside the options.xml the app crashes upon launch.I am referencing the image via the code below and showing the clickListener I am adding.
//ReturnHome is inside options.xml
//Adding this in my mainapp.java
returnHome = (ImageView)findViewById(R.id.returnHome);
returnHome.setOnClickListener(new OnClickListener(){
@Override
public void onClick(开发者_如何学JAVAView v) {
***APP CRASHES EVERY TIME WHEN I ADD THIS****
}
});
Trying to see if there was an error thrown but LogCat does not seem to show anything.
findViewById
for the returnHome image is in context of the application.
If in your applicaiton onCreate()
you set setContentView(R.layout.main);
when you call findViewById
it will be looking at main.xml
for the image returnHome
, which obviously isn't there because its on options.xml
, as a result you will get a NullPointerException, because if can't find what you are asking it to.
Instead of declaring the image listener for returnHome in the context of main.xml try doing it after changing the layout, maybe as a method:
private void changeView()
{
setContentView(R.layout.options);
returnHome = (ImageView)findViewById(R.id.returnHome);
returnHome.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// Perform whatever.....
}
});
}
Then change the first onclick listener to:
settings.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
changeView();
}
});
精彩评论