TogleButton
功能:有選中和未選中兩種狀態(tài),并且為不同的狀態(tài)設置不同的顯示文本蒋荚。
屬性:
android:checked="true"http://選中狀態(tài),默認為false
android:textOff="關"http://未選中顯示文本
android:textOn="開"http://選中狀態(tài)顯示文本-
效果:
- 實現(xiàn)思路:在xml布局文件中設置一個ToggleButton和一個ImageView速蕊。在Activity文件中初始化ToggleBuuton控件途乃,設置tb的OnCheckedChangeListener監(jiān)聽器俩功,重寫監(jiān)聽器的onCheckedChanged()方法幻枉,通過該方法的傳入?yún)?shù)isChecked,判斷tb的狀態(tài)诡蜓,改變相應圖片熬甫。
tog_bt.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:id="@+id/toggleButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textOn="開"
android:textOff="關"
android:checked="false"
/>
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/off"
/>
</LinearLayout>
TogBtActivity.java
package com.example.autodemo;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ToggleButton;
public class TogBtActivity extends ActionBarActivity implements OnCheckedChangeListener{
private ToggleButton tb;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tog_bt);
//初始化控件
tb=(ToggleButton) findViewById(R.id.toggleButton);
img=(ImageView) findViewById(R.id.imageView);
/**
* 給當前toggleButton設置監(jiān)聽器
*/
tb.setOnCheckedChangeListener(this);
}
/**
* 繼承onCheckedChangeListener接口后,重寫onCheckedChanged方法
*
* 當tb被點擊的時候蔓罚,當前的方法會被執(zhí)行椿肩,更換img的背景
*
* @param buttonView---代表被點擊控件的本身
* @param isChecked---代表被點擊的控件的狀態(tài)
*
*/
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//使用三目運算符,判斷isChecked的狀態(tài)豺谈,更換相應的img
img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
}
}