问题描述
是否有可能同时应用程序运行时改变矩形(在XML画)颜色的Java code?
Is it possible to change rectangle (drawn in xml) color in Java code while app is running?
我rectangle.xml:
My rectangle.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape">
<stroke android:width="2dp" android:color="#ffffff" />
<padding android:left="20dp"
android:top="20dp"
android:right="20dp"
android:bottom="20dp" />
<solid android:color="#006600" />
</shape>
在main.xml中得出:
Drawn in main.xml by:
<View
android:id="@+id/myRectangleView"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:background="@drawable/rectangle"/>
我试过这样:
GradientDrawable sd;
View viewrectangle;
viewrectangle = (View) findViewById(R.id.myRectangleView);
sd = (GradientDrawable) viewrectangle.getBackground();
sd.setColor(0xffffff00);
sd.invalidateSelf();
当我把它的OnCreate方法中起作用。
It only works when I put it inside OnCreate method.
我想通过一个按钮来改变矩形的颜色,所以我把这个code按钮的onClick()方法中。但是,当应用程序同时运行时颜色不会改变我点击按钮。有什么建议?
I want to change rect color by a button, so I put this code inside button's onClick() method. But when I click button while app is running color doesn't change. Any suggestions?
推荐答案
用于此code和它的工作,或者考虑使用viewrectangle.invalidate()重绘viewrectangle,但它不应该是nescarry:
Used this code and it worked, alternatively consider redrawing the viewrectangle using viewrectangle.invalidate(), but it shouldn't be nescarry:
View viewrectangle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewrectangle = (View) findViewById(R.id.myRectangleView);
}
public void doClick(View v) {
GradientDrawable sd = (GradientDrawable) viewrectangle.getBackground();
sd.setColor(0xffffff00);
sd.invalidateSelf();
}
在这个例子中,doClick()的方法被设置在main.xml中:
In this example the "doClick()" method is set in the main.xml:
<Button android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Button"
android:onClick="doClick"/>
这篇关于更改XML形状颜色,而应用程序正在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!