您的位置:首页 > 其它

通过GradientDrawable设置或修改view background

2017-01-13 14:21 190 查看
项目中遇到根据后台数据修改view背景色的要求。通过setBackground(color),虽然改变了颜色,但是也改变了圆角属性。

这里可以通过使用GradientDrawable来修改已经设置的shape中的颜色来达到目的。



比如,上图中TextView通过设置background实现上面左上、右下圆角的效果:

<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:paddingRight="8dp"
android:paddingLeft="8dp"
android:background="@drawable/bg_text"
android:text="理财"
android:textSize="14sp"
android:textColor="#ffffff"/>


bg_text.xml中代码:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<solid android:color="@color/red_f3323b"/>

<corners
android:bottomLeftRadius="0dp"
android:bottomRightRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="0dp"/>

</shape>


然后,在JAVA代码获取view的背景,然后再修改背景的颜色,便能实现只替换颜色。

GradientDrawable gd = (GradientDrawable)textview.getBackground();
gd.setColor("#679432");
holdView.typeTv.setBackground(gd);

同样,也可以直接在JAVA代码中直接设置背景

int roundRadius = 15;
int fillColor = Color.parseColor("#679432");
GradientDrawable gd = new GradientDrawable();
drawable gd.setColor(fillColor);
gd.setCornerRadius(roundRadius); //或者使用gd.setCornerRadii(new float[]{15,15,15,15,15,15,15,15})
textview.setBackground(gd);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐