按下时更改按钮背景-Android [英] Change Button Background when pressed - Android

查看:68
本文介绍了按下时更改按钮背景-Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个圆形的按钮。我要做的是在按下按钮时更改按钮颜色。有人可以告诉我如何将代码添加到后台xml吗?谢谢。

I have a button that is round shape. What I want to do is to change the button color when pressed. Can someone tell me how to add the codes to the background xml? Thank you.

<shape 
android:shape="rectangle" android:padding="10dp">
<solid android:color="#c0dfba"/>

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

</shape>


推荐答案

创建 XML 转换为 res / drawable / 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>
        <solid
            android:color="#343434" />
        <stroke
            android:width="1dp"
            android:color="#171717" />
        <corners
            android:radius="3dp" />
        <padding
            android:left="10dp"
            android:top="10dp"
            android:right="10dp"
            android:bottom="10dp" />
    </shape>
</item>
<item>
    <shape>
        <gradient
            android:startColor="#343434"
            android:endColor="#171717"
            android:angle="270" />
        <stroke
            android:width="1dp"
            android:color="#171717" />
        <corners
            android:radius="4dp" />
        <padding
            android:left="10dp"
            android:top="10dp"
            android:right="10dp"
            android:bottom="10dp" />
    </shape>
   </item>
</selector>

并设置为 Button Background like

And set to your Button as Background like

  <Button
    android:id="@+id/btnValidate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:background="@drawable/button"
    android:text="SOS Trasition"
    android:textColor="@android:color/white"
    android:textSize="16sp"
    android:textStyle="bold" />

如果要更改按钮文本颜色然后在 res / color / button_text.xml 中创建 XML 文件:

And if you want Change Button Text Color then create XML file at res/color/button_text.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
      android:color="#ffff0000"/> <!-- pressed -->
<item android:state_focused="true"
      android:color="#ff0000ff"/> <!-- focused -->
<item android:color="#ff000000"/> <!-- default -->
</selector>

并设置此布局 XML 将应用颜色列表到视图

And set this layout XML will apply the color list to a View:

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:textColor="@color/button_text" />

这篇关于按下时更改按钮背景-Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆