[英]How to use a StateListDrawable at runtime?
I have a problem with some code. 我的一些代码有问题。 I want to create a ColorPicker
DialogFragment
. 我想创建一个ColorPicker
DialogFragment
。 At the moment I use a GridView
and a custom BaseAdapter
to show some color shapes. 目前我使用
GridView
和自定义BaseAdapter
来显示一些颜色形状。 For each color I use a round ShapeDrawable
. 对于每种颜色,我使用圆形
ShapeDrawable
。 To set the color of the default state, I use the following code: 要设置默认状态的颜色,我使用以下代码:
getView() of my "ColorAdapter" 我的“ColorAdapter”的getView()
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(ctx);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Drawable drawable = ctx.getResources().getDrawable(R.drawable.color_item);
imageView.setBackground(drawable);
StateListDrawable states = (StateListDrawable) imageView.getBackground();
GradientDrawable shape = (GradientDrawable) states.getCurrent();
shape.setColor(colors[i]);
return imageView;
That works fine for me. 这对我来说很好。
But I want to change the color of an icon, when it is pressed. 但我想在按下时更改图标的颜色。 So I use a
StateListDrawable
. 所以我使用
StateListDrawable
。
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize="true" >
<item
android:state_pressed="true"
android:drawable="@drawable/circle" />
<item
android:drawable="@drawable/circle" />
</selector>
But, because I have different colors for each entry in the GridView
, I have to change the color of the state at runtime. 但是,因为我对
GridView
每个条目都有不同的颜色,所以我必须在运行时更改状态的颜色。
As you can see I use the same drawable resource for both states. 如您所见,我对两种状态使用相同的可绘制资源。 Maybe I can set the color of one state, as I do it with
states.getCurrent()
? 也许我可以设置一个状态的颜色,就像我使用
states.getCurrent()
?
I have also tried to use a ColorFilter
to decrease the brightness level. 我也尝试使用
ColorFilter
来降低亮度。 But when I try to do that, the ImageView
is always black, when it`s pressed. 但是当我尝试这样做时,
ImageView
总是很黑,当它被按下时。
Does anybody know how to do that? 有谁知道怎么做?
Ok, I found a solution. 好的,我找到了解决方案。 I use a
LayerDrawable
with two layers, the first one contains my shape, the second one a StateListDrawable
. 我使用了一个有两层的
LayerDrawable
,第一层包含我的形状,第二层包含StateListDrawable
。 This StateListDrawable
contains one empty shape for default state and one grey shape with lower alpha value. 此
StateListDrawable
包含一个用于默认状态的空形状和一个具有较低alpha值的灰色形状。 So now, when I press my color circle, the grey shape is put over my color shape. 所以,现在,当我按下我的色圈时,灰色的形状会被放在我的颜色形状上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.