Android开关控件ToggleButton

时间:2021-07-29 04:00:35

main.xml如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textOn="打开开关"
android:textOff="关闭开关"
android:background="@drawable/togglebutton_selector"
/>

</RelativeLayout>


togglebutton_selector.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/a" android:state_checked="true"/>
<item android:drawable="@drawable/b"/>
</selector>


mainActivity如下:

package c.c;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ToggleButton;
import android.app.Activity;
/**
* Demo描述:
* 利用ToggleButton表示状态的改变时
* 并且在状态改变时切换ToggleButton中的文字和图片
*
*/
public class MainActivity extends Activity {
private ToggleButton mToggleButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init(){
mToggleButton=(ToggleButton) findViewById(R.id.toggleButton);
mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
System.out.println("999999999");
} else {
System.out.println("8888888888");
}
}
});
}

}