溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Android開(kāi)發(fā)之ToggleButton實(shí)現(xiàn)開(kāi)關(guān)效果示例

發(fā)布時(shí)間:2020-10-03 19:25:38 來(lái)源:腳本之家 閱讀:128 作者:LoveJulin 欄目:移動(dòng)開(kāi)發(fā)

本文實(shí)例講述了Android使用ToggleButton實(shí)現(xiàn)開(kāi)關(guān)效果的方法。分享給大家供大家參考,具體如下:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >
  <ToggleButton
    android:checked="false"
    android:textOn="開(kāi)"
    android:textOff="關(guān)"
    android:id="@+id/toggleButton1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />
  <ImageView
    android:id="@+id/imageView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/off"
    />
</LinearLayout>

MainActivity.java

package com.example.hello;
import android.support.v7.app.ActionBarActivity;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ToggleButton;
import android.os.Bundle;
public class MainActivity extends ActionBarActivity implements OnCheckedChangeListener {
  private ToggleButton tb;
  private ImageView img;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //初始化控件
    tb = (ToggleButton) findViewById(R.id.toggleButton1);
    img = (ImageView) findViewById(R.id.imageView1);
    //給當(dāng)前的tb設(shè)置監(jiān)聽(tīng)器
    tb.setOnCheckedChangeListener(this);
  }
  @Override
  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    /*
     * 當(dāng)tb被點(diǎn)擊的時(shí)候,執(zhí)行當(dāng)前方法
     * buttonView 代表被點(diǎn)擊的控件本身
     * isChecked 代表被點(diǎn)擊的控件的狀態(tài)
     *
     * 當(dāng)點(diǎn)擊tb的時(shí)候,更換img的背景
     */
    img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
  }
}

更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Android開(kāi)發(fā)入門(mén)與進(jìn)階教程》、《Android調(diào)試技巧與常見(jiàn)問(wèn)題解決方法匯總》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》

希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI