原谅标题 - 不确定如何说出这个问题。
我在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的子项,找到形状,然后改变它。
我该怎么做?
谢谢!
答案 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();
}
});
}
}