Android --ToggleButton的使用

1. 效果图

 

2. 实现代码

firstActivity.java

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final ImageView imageView=(ImageView)findViewById(R.id.imageView1);     //获取对象
        ToggleButton toggleButton=(ToggleButton)findViewById(R.id.toggleButton1);    //获取对象
        toggleButton.setTextOff("关闭");                                    //设置未选中的文本
        toggleButton.setTextOn("打开");                                    //设置选中的文本
        toggleButton.setChecked(true);                                        //设置按钮状态

        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                                                    //设置监听器
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if(isChecked)
                {
                    imageView.setImageResource(R.drawable.bulb_on);        //开灯
                }
                else
                {
                    imageView.setImageResource(R.drawable.bulb_off);        //关灯
                }
            }
        });


    }

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LL"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/tv1" >
    </TextView>

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton" >
    </ToggleButton>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon" >
    </ImageView>

</LinearLayout>

 

3. 使用图片 (右键另存为,既可以使用)

     
 

 

posted @ 2014-09-26 10:06  落寞回头不如华丽转身  阅读(239)  评论(0编辑  收藏  举报