Android中自定义drawable资源实现布局的圆角边框效果

布局的圆角边框效果图如下所示:

这里写图片描述

如上图红色标注的部分就是一个圆角边框效果的自定义搜索框。


实现起来很简单,让布局(Relativelayout或者LinearLayout)的background属性引用自定义的drawable资源即可。

android:background="@drawable/bg_shape"

自定义drawable资源如下所示:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- 表示shape的四个角的角度。只适用于矩形shape,这里的角度是指圆角的程度 -->
    <corners android:radius="50dp" />

    <!-- 这个标签表示纯色填充,通过android:color即可指定shape中填充的颜色 -->
    <solid android:color="@color/white" />

    <!-- Shape的描边,下面指定了描边的宽度和描边的颜色 -->
    <stroke
        android:width="1dp"
        android:color="@color/blue" />

</shape>

xml布局中的代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context="com.example.mysearchview.MainActivity" >

    <LinearLayout
        android:id="@+id/ll1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@drawable/bg_shape"
        android:orientation="horizontal" >
    </LinearLayout>


</LinearLayout>

效果图如下所示:

这里写图片描述


其实上面的drawable资源确切点说应该叫做ShapeDrawable,它是一种很常见的Drawable,可以理解为通过颜色来构造的图形,它既可以是纯色的图形,也可以是具有渐变效果的图形。
需要注意的是标签创建的Drawable,其实体类实际上是GradientDrawable,下面说一下android:shape属性的含义。

android:shape
表示图形的形状,有四个选项:rectangle(矩形)、oval(椭圆)、line(横线)和ring(圆环)。它的默认值是矩形。

由于该属性的默认值是矩形,所以实现圆角效果的时候,该属性也可以不指定,因为默认就是矩形。


每天进步一点点!加油!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值