ToggleButton是android给我们提供的开关按钮,
有两种状态:选中和未选择状态。
以下是代码实例: main.xml
[html]
view plain
copy
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="fill_parent" android:background="#FFF5F5F5"
- android:layout_height="fill_parent">
- <LinearLayout android:layout_width="fill_parent"
- android:layout_height="wrap_content" android:orientation="horizontal">
- <TextView android:textSize="14.0sp" android:id="@+id/tvSound" android:textColor="@android:color/black"
- android:layout_width="wrap_content" android:layout_height="wrap_content"
- android:text="已开启" />
- <ToggleButton
- android:id="@+id/tglSound" android:background="@drawable/selector_butn_toggle"
- android:layout_width="wrap_content" android:layout_height="wrap_content"
- android:checked="true" android:textOn="" android:textOff=""
- android:text="" />
- </LinearLayout>
- </LinearLayout>
[java]
view plain
copy
- 这是主MainActivity
- package com.apkbus.toggle;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.Window;
- import android.widget.CompoundButton;
- import android.widget.CompoundButton.OnCheckedChangeListener;
- import android.widget.TextView;
- import android.widget.ToggleButton;
- public class MainActivity extends Activity implements OnCheckedChangeListener{
- private ToggleButton mToggleButton;
- private TextView tvSound;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题栏
- setContentView(R.layout.main);
- initView();//初始化控件方法
- }
- private void initView() {
- mToggleButton = (ToggleButton) findViewById(R.id.tglSound); //获取到控件
- mToggleButton.setOnCheckedChangeListener(this);//添加监听事件
- tvSound = (TextView) findViewById(R.id.tvSound);
- }
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- if(isChecked){
- tvSound.setText("已开启");
- }else{
- tvSound.setText("已关闭");
- }
- }
- }
这是效果图
实现起来相当简单, 供新手们参考。
源码下载:http://pan.baidu.com/share/link?shareid=413709&uk=1796216265