I'm trying to get the backgound of the layout to change based on what's in a textview. I know how to set the background in Java:
mainbg.setBackgroundResource(R.drawable.erburrows);
but if I wrap that call in an if statement, nothing happens. There are no error flags or anything, it just doesn't display anything in the background. Here's the code I'm using:
//--- BACKGROUND CHANGE ---
String tvString = showBook.getText().toString();
bookDisp.setText(tvString);
View mainbg = bgview.getRootView();
if(bookDisp.equals("Green Eggs")){
mainbg.setBackgroundResource(R.drawable.seuss);
}else if (bookDisp.equals("Tarzan")){
mainbg.setBackgroundResource(R.drawable.erburrows);
}
//--- END BACKGROUND CHANGE ---
Any idea why it doesn't work?
You are setting the text on bookDisp
(I guess that this is the TextView
) and then instead of using the text from that TextView
you do a compare between the TextView
object( bookDisp
) and the test String
that will fail. You'll probably want to do:
if(tvString.equals("Green Eggs")){
mainbg.setBackgroundResource(R.drawable.seuss);
}else if (tvString.equals("Tarzan")){
mainbg.setBackgroundResource(R.drawable.erburrows);
}
//...
if tvString
is the text from the target TextView
or get the string:
bookDisp.getText().toString()
尝试:
mainbg.setBackgroundDrawable(getResources().getDrawable(R.drawable.erburrows));
if(bookDisp.equals("Green Eggs")){
mainbg.setBackgroundResource(R.drawable.seuss);
}else if (bookDisp.equals("Tarzan")){
mainbg.setBackgroundResource(R.drawable.erburrows);
}
replace the above code with below and try:::
if(bookDisp.getText().toString().equals("Green Eggs")){
mainbg.setBackgroundResource(R.drawable.seuss);
}else if (bookDisp.getText().toString().equals("Tarzan")){
mainbg.setBackgroundResource(R.drawable.erburrows);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.