当前位置: 代码迷 >> Android >> Android自学札记之ToggleButton(开关按钮)的功能、特殊属性、用法
  详细解决方案

Android自学札记之ToggleButton(开关按钮)的功能、特殊属性、用法

热度:40   发布时间:2016-04-27 23:11:54.0
Android自学笔记之ToggleButton(开关按钮)的功能、特殊属性、用法
1.ToggleButton属性:
1>有两种状态:选中和未选中状态并需要为不同的状态设置不同的显示文本
2>android:checked="true"
3>android:textOff="关"(默认状态)
4>android:textOn="开"
2.使用方法:(example)
public class MainActivity extends Activity implements onCheckedChangeListener{
1>初始化控件
2>给控件赋值
3>给控件设置监听器
4>重写onCheckedChanged()方法{
//当控件被点击时执行,isChecked代表被点击的控件的状态
imageView.setBackGroundResource(isChecked?R.drawable.on:R.drawable.off);
  }

}

下面看一下具体代码的实现:为了大家观看方便我设置了两张图片,开的时候是一张图片,关的时候是两一张图片

首先是:activity_main.xml

<span style="font-family:KaiTi_GB2312;"><ToggleButton        android:checked="false"        android:textOn="开"        android:textOff="关"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/toggleButton"        />    <ImageView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/imageView"        android:layout_below="@+id/toggleButton"        android:background="@drawable/on"         /></span>

最后是:MainActivity.class

<span style="font-family:KaiTi_GB2312;">package com.example.administrator.togglebutton1;import android.content.DialogInterface;import android.media.Image;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.CompoundButton;import android.widget.ImageView;import android.widget.ToggleButton;public class MainActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {    private ToggleButton tb;    private ImageView img;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        tb = (ToggleButton) findViewById(R.id.toggleButton);  //初始化        img = (ImageView)findViewById(R.id.imageView);        tb.setOnCheckedChangeListener(this);    //   给控件设置监听器    }    @Override    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {  //重写onCheckedChanged()方法       //当控件被点击时执行,isChecked代表被点击的控件的状态        img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.ic_adc);    }}</span>


版权声明:本文为博主原创文章,未经博主允许不得转载。

  相关解决方案