Android實現按鈕點擊效果(第一次點擊變色,第二次恢複),android按鈕

來源:互聯網
上載者:User

Android實現按鈕點擊效果(第一次點擊變色,第二次恢複),android按鈕

1、首先建立一個按鈕

<Button

android:id="@+id/click"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="點擊變色"

android:background="@drawable/btn_st"

android:gravity="center"/>

2、1中建立的按鈕的background用到了btn_st,在drawable下建立btn_st

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_activated="true" android:drawable="@drawable/color1"></item> <!-- 未點擊時的顏色 -->

<item android:state_activated="false" android:drawable="@drawable/color2"></item> <!-- 點擊後的顏色 -->

</selector>

3、在2中用到的color1和color2,在values的strings中添加

<drawable name="color1">#339966</drawable>

<drawable name="color2">#fff</drawable>

4、java代碼

(1)首先擷取button 

  Button clickbtn =  (Button) findViewById(R.id.click);

(2)設定一個標記flag

  int flag = 0;

(3)給按鈕添加監聽事件

  clickbtn.setOnClickListener(new Button.OnClickListener() {

public void onClick(View v) {

switch(flag){

  case 0:

    mBtn[i].setActivated(false);

    flag = 1;

    break;

  case 1:

    mBtn[i].setActivated(true);

    flag = 0;

    break;

    }

  }

}

思路:給按鈕設定啟用/未啟用兩種不同顏色。當按鈕點擊一次、三次等奇數次時設定按鈕為未啟用狀態(按下),當按鈕點擊偶數次是設定為啟用狀態(未按下)。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.