ET.
ET.

Reputation: 1969

Uncleared StateListDrawable behavior on Android

I have very strange phenomenon when I try to use StateListDrawable:

I have a view that extends ImageView, where I use StateListDrawable in its constructor. I have 2 code snippets, to present my problem. The first one:

public class MyView extends ImageView{  
Resources r = getResources();
Drawable filteredDrawable = r.getDrawable(R.drawable.smallsale);                    
filteredDrawable.setColorFilter(new LightingColorFilter(Color.RED, 1));                                     
setImageDrawable(filteredDrawable); 
}

And the second one:

public class MyView extends ImageView{
Resources r = getResources();
Drawable filteredDrawable = r.getDrawable(R.drawable.smallsale);

filteredDrawable.setColorFilter(new LightingColorFilter(Color.RED, 1));

StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},  filteredDrawable);
states.addState(new int[] {android.R.attr.state_focused}, filteredDrawable);
states.addState(new int[] {}, r.getDrawable(R.drawable.smallsale));

//Notice I do not use 'states' at all...
setImageDrawable(filteredDrawable); 

}

(I know this code does not make a lot of sense - I wanted to simplify the problem to make the question clearer). The problem is that on the first sinppet everything works fine - I set a color filter on the drawable and it is shown. But on the second snippet, the StateListDrawable instance effects somehow on the filter, and the original drawable is being shown, even though I never connected it to the ImageView by calling setImageDrawable(states).

Can some one explain to me what is going on? My goal is to use the StateListDrawable with the same drawable for different states as follow:

StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},  filteredDrawable);
states.addState(new int[] {android.R.attr.state_focused}, filteredDrawable);
states.addState(new int[] {}, r.getDrawable(R.drawable.smallsale));
setImageDrawable(states);

(I need to do it by code because my drawable should be loaded dynamically from the net, and not as a resource)

Upvotes: 5

Views: 1316

Answers (1)

ET.
ET.

Reputation: 1969

Ok. I found this post

It turns out that StateListDrawables looses the filter for some reason... I took SnoK's solution and it works great for me.

I dont know why Google does not feel it should be noted on the docs as a side effect...

Upvotes: 3

Related Questions