简体   繁体   English

更改<Button>onClick的颜色?</button>

[英]Change <Button> color onClick?

<Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="Add"
        android:id="@+id/btnAdd"
        android:background="#ff6347"
        android:textColor="#f8f8f8"
        android:layout_marginTop="36dp"
        android:clickable="true"
        android:layout_below="@+id/txtAddress"
        android:layout_centerHorizontal="true"
        android:focusable="true" />

This is my XML Button element and it's fine and dandy...but I want it to be known when it's pressed. 这是我的XML Button元素,很好,很花哨……但是,我希望它在按下时被人们知道。 How can I go about making it have different styling when pressed vs when not pressed? 在按下和未按下时如何使它具有不同的样式?

You can use a selector and use a drawables for different states. 您可以使用选择器,并为不同的状态使用可绘制对象。

http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

You can also use OnTouchListener and on ACTION_DOWN and ACTION_UP set the color to the buttons 您还可以使用OnTouchListener并在ACTION_DOWNACTION_UP颜色设置为按钮

You want to use a selector as the background for the button. 您要使用选择器作为按钮的背景。 Basically you can define the the different shape you want for each state of the button and the shape consists of color, corner radius, and other cool things. 基本上,您可以为按钮的每种状态定义所需的不同形状,并且该形状由颜色,角半径和其他炫酷元素组成。

XML file saved at res/drawable/button.xml: 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"> <!-- pressed -->
            <shape android:shape="rectangle" >
                <solid android:color="@color/blue" />
            </shape>
        </item>
        <item> <!-- default -->
            <shape android:shape="rectangle" >
                <solid android:color="@color/red" />
            </shape>
        </item>
    </selector>

This layout XML applies the state list drawable to a Button: 此布局XML将可绘制的状态列表应用于Button:

<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/button" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM