Android控件之ToggleButton(多狀態按鈕)


一、概述

  ToggleButton有兩種狀態:選中狀態和沒選中狀態(類似一個開關),並且需要為不同的狀態設置不同的顯示文本

 

二、ToggleButton屬性

  android:checked = "true"  ——按鈕的狀態(true為選中(textOn),false為沒有選中(textOff))

  android:textOff = "關"

  android:textOn = "開"  

 

 

三、代碼演示

  1、先將下面兩個圖片放入到資源文件中(分別命名為off和on)

      

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textOn="開"
        android:textOff="關" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/off" />
    
</LinearLayout>
package com.muke.textview_edittext;

import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ToggleButton;
import android.app.Activity;


public class MainActivity extends Activity 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);
        
        //給當前的tb控件設置監聽器
        tb.setOnCheckedChangeListener(this);
        
    }
    
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //當tb被點擊的時候,當前的方法會執行
        //buttonView——代表被點擊控件的本身
        //isChecked——代表被點擊的控件的狀態
        //當點擊tb這個控件的時候更好img的src
        
        img.setImageResource(isChecked?R.drawable.on:R.drawable.off);//在java代碼中設置ImageView控件的src路徑(這里使用三元運算來設置圖片的路徑)
        
    }
}

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM