ToggleButton控件的使用

来源:互联网 发布:suse linux 修改时间 编辑:程序博客网 时间:2024/07/17 20:39

ToggleButton常用属性说明:

android:textOff 按钮未被选中时显示的文本内容

android:textOn按钮被选中时显示的文本内容


1.strings.xml

<resources>      <string name="app_name">TestActivity</string>     <string name="menu_settings">Settings</string>     <string name="title_activity_main">MainActivity</string>     <string name="on">开灯</string>     <string name="off">关灯</string>  </resources>

2.main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="vertical"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:background="@color/black" >     <ImageView         android:id="@+id/imageView01"         android:src="@drawable/bulb_off"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="center_horizontal"/>     <ToggleButton         android:id="@+id/toggleButton01"         android:textOn="@string/on"         android:textOff="@string/off"         android:layout_width="140dp"         android:layout_height="wrap_content"         android:layout_gravity="center_horizontal"/> </LinearLayout>

3.Activity代码

package com.example.testactivity;  import android.os.Bundle; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.ToggleButton; import android.app.Activity;  public class MainActivity extends Activity {  ToggleButton toggleButton=null; ImageView imageView=null;     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);         toggleButton=(ToggleButton) findViewById(R.id.toggleButton01);         toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener(){  @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub setBulbState(isChecked); }                  });     }       public void setBulbState(Boolean state){     //设置图片状态     imageView=(ImageView) findViewById(R.id.imageView01);     imageView.setImageResource((state)?R.drawable.bulb_on:R.drawable.bulb_off);     //设置toggleButton状态     toggleButton=(ToggleButton) findViewById(R.id.toggleButton01);     toggleButton.setChecked(state);     }      }

4程序运行图




原创粉丝点击