Toggle Background View

I have a View object in my activity, and I would like to change the background resource of the view. In particular, I would like to switch it.

So, I need this logic:

if (myView.getBackgroundResource() == R.drawable.first) {
  myView.setBackgroundResource(R.drawable.second);
}
else {
  myView.setBackgroundResource(R.drawable.first);
}

The problem is that there is no getBackgroundResource () method.

How can I get the resource that View uses for its background?

+3
source share
5 answers

I donโ€™t think View remembers which resource it uses after it gets Drawable from the resource.

Why not use an instance variable in your activity or a subclass of View and add an instance variable to it?

0
source

, ? .

int[] backgrounds = {
    R.drawable.first,
    R.drawable.second,
    R.drawable.third
};

int currentBg;

void switch() {
    currentBg++;
    currentBg %= backgrounds.length;

    myView.setBackgroundResource(backgrounds[currentBg]);
}
0

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;
}

mCurrentBg, .

0

getResources().getIdentifier("filename", "drawable", "com.example.android.project");. , , (, - ) , .

0

: โ€‹โ€‹ .

, setTag() getTag() :

//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 theoretically. The downside is that you add a little overhead if you manually flag it for the first time, but after the initial marking you donโ€™t have to worry about tracking flags.

0
source

Source: https://habr.com/ru/post/1795606/


All Articles