[英]Uncleared StateListDrawable behavior on Android
I have very strange phenomenon when I try to use StateListDrawable
: 当我尝试使用StateListDrawable
时,我有一个非常奇怪的现象:
I have a view that extends ImageView
, where I use StateListDrawable
in its constructor. 我有一个扩展ImageView
的视图,我在其构造函数中使用StateListDrawable
。 I have 2 code snippets, to present my problem. 我有2个代码片段,以提出我的问题。 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. 问题是,在第一次正确的时候一切正常 - 我在drawable上设置了一个彩色滤镜,并显示出来。 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)
. 但在第二个片段中, StateListDrawable
实例以某种方式影响过滤器,并显示原始 drawable,即使我从未通过调用setImageDrawable(states)
将其连接到ImageView
。
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: 我的目标是使用具有相同drawable的StateListDrawable
用于不同的状态,如下所示:
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) (我需要通过代码来实现,因为我的drawable应该从网络动态加载,而不是作为资源加载)
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. 事实证明StateListDrawables
由于某种原因失去了过滤器......我采用了SnoK的解决方案,它对我很有用。
I dont know why Google does not feel it should be noted on the docs as a side effect... 我不知道为什么谷歌不认为应该在文档上注明副作用...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.