Android上未清除的StateListDrawable行为

前端之家收集整理的这篇文章主要介绍了Android上未清除的StateListDrawable行为前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我尝试使用StateListDrawable时,我有一个非常奇怪的现象:

我有一个扩展ImageView的视图,我在其构造函数中使用StateListDrawable.
我有2个代码片段,以提出我的问题.
第一个:

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

第二个:

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

}

(我知道这段代码没有多大意义 – 我想简化问题以使问题更清晰).问题是,在第一次正确的时候一切正常 – 我在drawable上设置了一个彩色滤镜,并显示出来.但在第二个片段中,StateListDrawable实例以某种方式影响过滤器,并显示原始drawable,即使我从未通过调用setImageDrawable(states)将其连接到ImageView.

有人可以向我解释发生了什么事吗?
我的目标是使用具有相同drawable的StateListDrawable用于不同的状态,如下所示:

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

(我需要通过代码来实现,因为我的drawable应该从网络动态加载,而不是作为资源加载)

解决方法

好.
我找到了 this post

事实证明StateListDrawables由于某种原因失去了过滤器……
我采用了SnoK的解决方案,它对我很有用.

我不知道为什么谷歌不认为应该在文档上注明副作用…

猜你在找的Android相关文章