簡體   English   中英

按下按鈕后如何使按鈕變色?

[英]How do I make the button change color when it's pressed?

我對android編程有點陌生,所以我對自己的工作一無所知。 我想在按下按鈕時使按鈕改變顏色。 到目前為止,這是我的按鈕的外觀:

<Button
    android:id="@+id/c1"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="#FFFFFF" >

</Button>

我必須添加什么才能使其在按下時變色?

定義按鈕選擇器並將其設置為按鈕background

選擇器:

button_selector.xml

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

<item android:state_focused="true" android:drawable="@color/pressed_button_clr"></item>
<item android:state_pressed="true" android:drawable="@color/pressed_button_clr"></item>
<item  android:drawable="@color/default_button_clr"></item>
</selector>

xml代碼是:

<Button
    android:id="@+id/c1"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/button_selector" >

</Button>

因為您要定義自己的背景色,所以按鈕看起來好像沒有被單擊一樣,因此,如果刪除定義的背景色,它將看起來像單擊一樣。 為了定義自己的背景色,您必須創建一個自定義按鈕

創建一個自定義按鈕

創建與您想要的顏色匹配的形狀

按鈕點擊形狀

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <stroke 
        android:width="1dp" 
        android:color="#505050"/>

    <size android:width="180dp"
        android:height="40dp"/>

    <solid android:color="#505050"/>

</shape>

按鈕正常形狀

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

    <size android:width="180dp"
     android:height="40dp"/>

     <solid android:color="#4ddedede"/>

</shape>

創建這兩個形狀后,請創建按鈕以使用它們

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM