1>有兩種狀態:選中和未選中狀態並需要爲不同的狀態設置不同的顯示文本
2>android:checked="true"
3>android:textOff="關"(默認狀態)
4>android:textOn="開"
2.使用方法:(example)
public class MainActivity extends Activity implements onCheckedChangeListener{
1>初始化控件
2>給控件賦值
3>給控件設置監聽器
4>重寫onCheckedChanged()方法{
//當控件被點擊時執行,isChecked代表被點擊的控件的狀態
imageView.setBackGroundResource(isChecked?R.drawable.on:R.drawable.off);
}
}
下面看一下具體代碼的實現:爲了大家觀看方便我設置了兩張圖片,開的時候是一張圖片,關的時候是兩一張圖片
首先是:activity_main.xml
<span style="font-family:KaiTi_GB2312;"><ToggleButton
android:checked="false"
android:textOn="開"
android:textOff="關"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toggleButton"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView"
android:layout_below="@+id/toggleButton"
android:background="@drawable/on"
/>
</span>
最後是:MainActivity.class
<span style="font-family:KaiTi_GB2312;">package com.example.administrator.togglebutton1;
import android.content.DialogInterface;
import android.media.Image;
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.ImageView;
import android.widget.ToggleButton;
public class MainActivity extends ActionBarActivity implements CompoundButton.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.toggleButton); //初始化
img = (ImageView)findViewById(R.id.imageView);
tb.setOnCheckedChangeListener(this); // 給控件設置監聽器
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //重寫onCheckedChanged()方法
//當控件被點擊時執行,isChecked代表被點擊的控件的狀態
img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.ic_adc);
}
}</span>