访问XML可绘制资源中元素的属性

时间:2014-07-08 21:59:49

标签: android android-layout android-ui

原谅标题 - 不确定如何说出这个问题。

我在rectangle.xml内创建了一个名为res/drawable的文件。这是一个非常基本的矩形形状,我在自定义列表视图中使用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的子项,找到形状,然后改变它。

我该怎么做?

谢谢!

2 个答案:

答案 0 :(得分:1)

试过了,我设法做到了。

ImageView imageView = (ImageView) findViewById(R.id.row_colorRect);
((GradientDrawable) imageView.getDrawable()).setColor(Color.RED);

访问代表您的ImageView资源的GradientDrawable rectangle.xml,您可以更改其纯色以及其他属性。

答案 1 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

shape.xml(可绘制)

<?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>

<强> main.xml中

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

<强> MyActivity.java

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

}