Android 访问XML可绘制资源中元素的属性
请原谅标题-不知道这个问题怎么说 我在Android 访问XML可绘制资源中元素的属性,android,android-layout,android-ui,Android,Android Layout,Android Ui,请原谅标题-不知道这个问题怎么说 我在res/drawable内部创建了一个名为rectangle.xml的文件。这是一个非常基本的矩形形状,我在自定义listview中与ImageView一起使用 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <
res/drawable
内部创建了一个名为rectangle.xml
的文件。这是一个非常基本的矩形形状,我在自定义listview中与ImageView一起使用
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#FF0000" />
<corners android:radius="4dp"/>
</shape>
像这样使用它:
<ImageView
android:id="@+id/row_colorRect"
android:layout_width="24dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@drawable/rectangle" />
我希望能够访问该矩形的solid
属性,以便可以动态更改其颜色。我无法通过ImageView访问该属性。。所以我想我必须以某种方式挖掘ImageView的子对象,找到形状,并以这种方式进行更改
我该怎么办
谢谢 刚刚试过,我成功了
ImageView imageView = (ImageView) findViewById(R.id.row_colorRect);
((GradientDrawable) imageView.getDrawable()).setColor(Color.RED);
访问表示您的
矩形.xml
资源的ImageView
GradientDrawable
,您可以更改其纯色和其他属性。尝试这种方法,希望这将帮助您解决问题。
shape.xml(可绘制)
我从未这样做过,但您可以尝试创建两个具有不同属性的不同形状,然后以编程方式更改ImageView的源。这非常有效,谢谢。我是不是走错路了?我只希望在我的每个ListView行上有彩色的指示器,并且我希望能够根据行的“状态”更改它们的颜色。但每个回复的人似乎都从未尝试过这样的事情。。让我觉得我在用一种不寻常的方式做这件事。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#FF0000" />
<corners android:radius="4dp"/>
</shape>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/shape"/>
</LinearLayout>
public class MyActivity extends Activity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GradientDrawable sd = (GradientDrawable) imageView.getBackground().mutate();
sd.setColor(Color.parseColor("#CCC111"));
sd.invalidateSelf();
}
});
}
}