Toggling View background
I have a View object on my Activity and 开发者_JAVA百科I'd like to change the background resource of the view. More specifically, I'd like to toggle it.
So I'll need some logic like this:
if (myView.getBackgroundResource() == R.drawable.first) {
myView.setBackgroundResource(R.drawable.second);
}
else {
myView.setBackgroundResource(R.drawable.first);
}
The issue here being that there is no getBackgroundResource() method.
How can I obtain the resource a View is using for its background?
I don't think the View remembers what resource it is using after it gets the Drawable from the resource.
Why not use an instance variable in your Activity, or subclass the View and add an instance variable to it?
Wouldn't it be easier to just have a control variable that maintains the state? Lets you be flexible and allows you any number of drawables.
int[] backgrounds = {
R.drawable.first,
R.drawable.second,
R.drawable.third
};
int currentBg;
void switch() {
currentBg++;
currentBg %= backgrounds.length;
myView.setBackgroundResource(backgrounds[currentBg]);
}
You could use a flag to keep track of which was last set
private static final int FIRST_BG = 0;
private static final int SECOND_BG = 1;
private int mCurrentBg;
...
if (mCurrentBg == FIRST_BG) {
myView.setBackgroundResource(R.drawable.second);
mCurrentBg = SECOND_BG;
}
else {
myView.setBackgroundResource(R.drawable.first);
mCurrentBg = FIRST_BG;
}
You would have to initialize mCurrentBg
wherever the background is initially set though.
You can get the ID of a resource via the getResources().getIdentifier("filename", "drawable", "com.example.android.project");
function. As you can see you will need the filename, the type of resource (drawable, layout or whatever) and the package it is in.
EDIT: Updated my logic fail.
I think you might be able to put the setTag()
and getTag()
methods to use here:
//set the background and tag initially
View v = (View)findViewById(R.id.view);
v.setBackgroundResource(R.drawable.first);
v.setTag(R.drawable.first);
if(v.getTag().equals(R.drawable.first)) {
v.setBackgroundResource(R.drawable.second);
v.setTag(R.drawable.second);
} else {
v.setBackgroundResource(R.drawable.first);
v.setTag(R.drawable.first);
}
I have not tested this, but I think it should work, in theory. The downside is that you add a little overhead by having to manually tag it the first time, but after the initial tagging, you shouldn't have to worry about keeping track of flags.
精彩评论