安卓中自定义点击按钮,点击可以改变颜色

安卓中自定义点击按钮,点击可以改变颜色

效果如下:

不点击的时候的状态为:

1)给一个Button设置一个圆角矩形的背景。
2)正常情况圆角矩形的边框是蓝色,填充颜色是灰色
3)当按钮被按下的时候圆角矩形的边框是红色的, 内部颜色是渐变颜色,渐变方向从右到左 红-->蓝


首先我们要定义一个选择器:

在res目录下新建一个drawable目录,在drawable目录下新建一个color_button的xml文件,类型为selector



color_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >

<shape android:shape="rectangle">
    <stroke android:width="5dp"
            android:color="#f00"/>
    <corners android:radius="20dp"/>

    <gradient android:startColor="#f00"
              android:angle="180"
              android:endColor="#00f"/>
</shape>

</item>
<item android:state_pressed="false" >
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
           android:shape="rectangle"
            >
        <stroke android:width="5dp"
                android:color="#ff5a27cc"/>
        <corners android:radius="20dp"/>
        <solid android:color="#ffcccccc"/>

    </shape>
</item>

</selector>

第二步把我们定义的选择器加载到button中去

</pre>在button中用设置button的效果为刚才定义的效果<span style="font-size:18px;"><span style="font-size:18px;"></span></span><pre name="code" class="plain"> android:background="@drawable/color_button"

</pre><pre name="code" class="plain"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"

        >

    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Hello World, MainActivity"
            />

    <Button
            android:padding="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="我是一个按钮哦anannanan"
            android:background="@drawable/color_button"
            android:layout_gravity="center_horizontal"
       />
  
</LinearLayout>

最后我们直接运行到手机上就OK了,效果实现了。


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值