关于安卓开发实现双状态按钮

双状态按钮(Toggle)

xml文件代码

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical" >
 6     <ImageView android:layout_width="wrap_content"
 7         android:layout_height="wrap_content"
 8         android:src="@drawable/bulb_off"
 9         android:id="@+id/imageView"
10         android:layout_gravity="center_horizontal"
11         />
12     <ToggleButton android:layout_width="140dip"
13         android:layout_height="wrap_content"
14         android:textOn="打开"
15         android:textOff="关闭"
16         android:id="@+id/toggleButton"
17         android:layout_gravity="center_horizontal"
18         />
19 
20 </LinearLayout>
xml文件


java文件

 1 package lianxi;
 2 
 3 import java.security.PublicKey;
 4 
 5 import com.example.jichu_lianxi.R;
 6 
 7 import android.app.Activity;
 8 import android.os.Bundle;
 9 import android.widget.CompoundButton;
10 import android.widget.CompoundButton.OnCheckedChangeListener;
11 import android.widget.ImageView;
12 import android.widget.ToggleButton;
13 /*
14  * 双按钮
15  */
16 public class ToggleButton_lianxi extends Activity{
17     private ImageView imageView = null;                  //图片标签
18     private ToggleButton toggleButton = null;            //双状态按钮
19     
20     @Override
21     protected void onCreate(Bundle savedInstanceState) {
22         // TODO Auto-generated method stub
23         super.onCreate(savedInstanceState);
24     setContentView(R.layout.togglebutton_lianxi);
25     
26     imageView = (ImageView) findViewById(R.id.imageView);
27     toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
28     
29     //设置按钮响应
30     toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
31         
32         @Override
33         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
34             // TODO Auto-generated method stub
35             toggleButton.setChecked(isChecked);
36             //设置图片
37             imageView.setImageResource(isChecked?R.drawable.bulb_on:R.drawable.bulb_off);
38         }
39     });
40     
41     }
42         
43 }
ToggleButton_lianxi.java


效果图

posted @ 2013-04-03 12:23  听着music睡  阅读(589)  评论(0编辑  收藏  举报