在我们日常使用app的过程中,经常会见到开关按钮,点击控制开和关,这种功能在Android中可以通过ToggleButton控件来实现。
什么是ToggleButton?
ToggleButton有两种状态,选中和未选中状态,并且需要为不同的状态设置不同的值
常用属性:android:checked=”true”来控制是否打开,true为打开,默认为false
android:textOff=“关”当开关是关闭状态时显示的文本
android:textOn=“开”当开关是打开状态时显示的文本
下面用实例操作下:
1、创建项目ToggleButtonTest,修改activity_main.xml代码如下:
定义ToggleButton(开关按钮)和ImageView(用于相应开关操作)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.togglebutton.MainActivity" >
<ToggleButton
android:id="@+id/tb_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textOn="显示图片"
android:textOff="隐藏图片"
/>
<ImageView
android:id="@+id/image_show"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/picture"/>
</LinearLayout>
修改MainActivity.java代码,如下:
package com.example.togglebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
private ToggleButton tbImage;
private ImageView imageShow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tbImage = (ToggleButton) findViewById(R.id.tb_image);
imageShow = (ImageView) findViewById(R.id.image_show);
//通过匿名内部类的方法控制ToggleButton的开关点击事件
tbImage.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
//arg0是当前的ToggleButton控件,arg1是当前控件的checked属性的值,在xml中不设值,默认为false
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
//如果当前是false,即checked为false,让图片隐藏,负责显示
if(arg1)
imageShow.setVisibility(View.GONE);
else
imageShow.setVisibility(View.VISIBLE);
}
});
}
}
最终效果:
1、打开之后显示的
2、点击ToggleButton之后界面