改变形状边框颜色在运行时 [英] Change shape border color at runtime
问题描述
我有我的文件夹绘制这种形状:
I have this shape in my drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="#ffffff" />
<stroke android:width="2dp" android:color="#B5B5B5"/>
</shape>
这个定义与圆角的矩形,我可以把它作为背景适用于任何面板是这样的:机器人:背景=@可绘制/ round_corner_shape
This define a rectangle with rounded corners and I can apply it as background to any panel like this: android:background="@drawable/round_corner_shape".
下面问题来了:我有几个小组对我的应用程序,与相同形状的背景,但每个造型我想不同的边框(中风)的颜色。我不想创建3个形状,唯一的区别是在笔触颜色。 是否有可能在运行时更改行程值?
Here comes the question: I have few panels on my application, with the same shape as background, but for each shape I want a different border (stroke) color. I don't want to create 3 shapes, the only difference to be on the stroke color. Is it possible to change at runtime the stroke value?
推荐答案
我有同样的问题。 就我而言,我有一个GridView,这在网格中的项目可以有边框的颜色由用户在运行时改变。
I had the same problem. In my case, I had a GridView, which the items in grid could have the border color changed by the user at runtime.
所以,在gridviewAdapter为网格,我没有(一个生成的观点适配器)
So, in the gridviewAdapter for that grid, I did the following in the getView method (the one that generates the view for the adapter)
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.griditem, null);
GradientDrawable gradientDrawable = (GradientDrawable) convertView.getBackground();
gradientDrawable.setStroke(2, mColor);
convertView.invalidate();
return convertView;
}
mColor是重新presents的颜色,就像我们做的XML文件的INT。 在java中code,而不是#我们用0X在AARRGGBB格式定义它。 例如,使用0xFF000000 100%不透明的黑色和0xFF0000FF 100%不透明的蓝色。 自从谷歌API有益在这里解释这告诉INT的颜色是笔触颜色。
mColor is a int that represents the color, much like we do in the xml files. In java code, instead of "#" we use "0x" to define it in the AARRGGBB format. For example, use 0xFF000000 for 100% opaque BLACK and 0xFF0000FF for 100% opaque BLUE. Explaining this here since the google api 'helpfully' tells that the int color is "the color of the stroke".
这解决了我的问题。我想你可以尝试类似你的情况什么的。
This solved my problem... I guess you can try something similar for your case.
这篇关于改变形状边框颜色在运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!