android----ToggleButton&Switch

XML代码:

<ToggleButton
        android:id="@+id/firstToggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/sexGroup"
        android:layout_marginLeft="61dp"
        android:layout_marginTop="50dp"
     //android:textOn&Off是设置按钮开启时或关闭时显示的文字 android:textOn="ON" android:textOff="OFF" android:checked="true"/> <ToggleButton android:id="@+id/secondToggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/firstToggle" android:layout_below="@+id/firstToggle" android:layout_marginTop="23dp" android:textOn="ON" android:textOff="OFF" /> <Switch android:id="@+id/mySwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/secondToggle" android:layout_below="@+id/secondToggle" android:layout_marginTop="40dp" android:textOn="ON" android:textOff="OFF"/>

java代码:
注意这里使用的是CompoundButton.OnCheckedChangeListener

firstToggle=(ToggleButton)findViewById(R.id.firstToggle);
        firstToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    Toast.makeText(MainActivity.this, "你打开了--->>", 2).show();
                }else{
                    Toast.makeText(MainActivity.this, "你关上了--->>", 2).show();
                }
            }
        });
        secondToggle=(ToggleButton)findViewById(R.id.secondToggle);
        secondToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                System.out.println("---->>"+isChecked);
                if(isChecked){
                    Toast.makeText(MainActivity.this, "你打开了--->>", 2).show();
                }else{
                    Toast.makeText(MainActivity.this, "你关上了--->>", 2).show();
                }
            }
        });
        mySwitch=(Switch)findViewById(R.id.mySwitch);
        mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton btn, boolean isChecked) {
                if(isChecked){
                    Toast.makeText(MainActivity.this, "你打开了--->>", 2).show();
                }else{
                    Toast.makeText(MainActivity.this, "你关上了--->>", 2).show();
                }
            }
        });

 

posted @ 2014-02-19 13:05  一个人的秋千  阅读(262)  评论(0)    收藏  举报