shape的对应的代码写法

来源:互联网 发布:工信部 域名备案 编辑:程序博客网 时间:2024/06/06 05:57

在界面设置时,我们很多时候需要给控件加上圆角或边颜色的效果,一般来说我们可以设置其background为一个shape类型的drawable即可实现,类似代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"    android:id="@+id/ll_root"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_marginBottom="10dp"    android:background="@drawable/rec_bank_white_purple5"    android:orientation="horizontal"/>此背景即为drawable下的一个资源文件,类似代码如下:
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android">    <solid android:color="@color/white" />    <corners android:radius="5dp" />    <stroke        android:width="1dp"        android:color="@color/questionBankLightPurple" /></shape>我们通过代码 
ll_root.getBackground();
获取得drawable,发现其实返回的是一个 android.graphics.drawable.GradientDrawable;

因此我们就可以用代码来生成这个backgroud了

/** * 产生shape类型的drawable * * @param solidColor * @param strokeColor * @param strokeWidth * @param radius * @return */public static GradientDrawable getBackgroundDrawable(int solidColor, int strokeColor, int strokeWidth, float radius) {    GradientDrawable drawable = new GradientDrawable();    drawable.setColor(solidColor);    drawable.setStroke(strokeWidth, strokeColor);    drawable.setCornerRadius(radius);    return drawable;}

此方法对应上面的shape就一目了然了,这样在代码中使用可以实现ListView下有不同边框颜色的条目了,而不必要去生成过多的drawable资料文件。



0 0
原创粉丝点击