Android开关控件ToggleButton

来源:互联网 发布:兼职淘宝模特怎么入行 编辑:程序博客网 时间:2024/09/21 09:02

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;@Overrideprotected 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() {@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {                if (isChecked) {System.out.println("999999999");} else {System.out.println("8888888888");}}});    }}


 

原创粉丝点击