代码设置控件的背景

来源:互联网 发布:央视新闻数据动画小人 编辑:程序博客网 时间:2024/05/22 11:54
代码设置控件的背景为圆角并随机背景色:


说明:GradientDrawable相当于drawable中自定义shape的布局文件所生成的Drawable,所以它可以设置corners、solid、stroke等


布局文件中的写法(布局文件中无法设置随机色):
<shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle" >    <!-- 圆角半径 -->    <corners android:radius="6px" />    <!-- 填充颜色 -->    <solid android:color="随机色" /></shape>




java代码中的写法:
GradientDrawable background = new GradientDrawable();//得到随机颜色Random random = new Random();int alpha = 255;int red = random.nextInt(190)+30;//0-255 30-220int green = random.nextInt(190)+30;//30-220int blue = random.nextInt(190)+30;//30-220int argb = Color.argb(alpha, red, green, blue);//设置填充颜色background.setColor(argb);//设置圆角半径background.setCornerRadius(UIUtils.dip2Px(6));view.setBackgroundDrawable(background);//这setBackgroundDrawable(Drawable)是一个过时的方法


0 0