【问题标题】:Uncleared StateListDrawable behavior on AndroidAndroid 上未清除的 StateListDrawable 行为
【发布时间】:2023-03-27 06:06:01
【问题描述】:

我在尝试使用StateListDrawable时出现了很奇怪的现象:

我有一个扩展ImageView 的视图,我在其构造函数中使用StateListDrawable。 我有 2 个代码 sn-ps,来提出我的问题。 第一个:

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

}

(我知道这段代码没有多大意义——我想简化问题以使问题更清晰)。问题是在第一个sinppet 上一切正常——我在drawable 上设置了一个滤色器并显示出来。但是在第二个 sn-p 上,StateListDrawable 实例以某种方式对过滤器产生了影响,并且显示了 original 可绘制对象,即使我从未通过调用 setImageDrawable(states) 将其连接到 ImageView .

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

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

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

【问题讨论】:

    标签: android android-drawable


    【解决方案1】:

    好的。 我找到了this post

    原来StateListDrawables 出于某种原因丢失了过滤器... 我采用了 SnoK 的解决方案,它对我很有用。

    我不知道为什么 Google 认为不应该在文档中注明它的副作用...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多