Android UI(ToggleButton)详解

2015年7月2日09:28:31 发表评论 37 views

1.应用场景

ToggleButton与Switch和CheckBox类似,具备两种状态,而CheckBox的主要场景在于数据的的单项选择比如,人的性别,而ToggleButton与Switch应用于程序中两种状态的切换。

2.常用属性

1. 继承Button的相关属性

2.android:textOn="关闭"//设置按钮开启时显示的文本

3.android:textOff="打开"//设置按钮关闭时显示的文本

4.android:checked="true"//设置按钮是否被选中,默认未选中

3.事件监听与基本使用

xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.andy.androiduitogglebutton.MainActivity" >
        <ToggleButton
            android:id="@+id/togglebutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textOn="打开"
            android:textOff="关闭"
            android:checked="true"/>
</LinearLayout>

Java代码:

package com.andy.androiduitogglebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
	private ToggleButton togglebutton;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//初始化togglebutton
		togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
		//设置监听器
		togglebutton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, Boolean isChecked) {
				if(isChecked){
					Toast.makeText(MainActivity.this, "打开", Toast.LENGTH_lONG).show();
				} else{
					Toast.makeText(MainActivity.this, "关闭", Toast.LENGTH_lONG).show();
				}
			}
		});
	}
}

4.自定义ToggleButton

4.1 先上截图,顺序和文章顺序一致,第一个为普通实现,第二个为Selector自定义点击切换ToggleButton, 第三个为java代码自定义可拖动ToggleButton。

Android UI(ToggleButton)详解

4.1 Selector自定义点击切换ToggleButton

1)制作图片导入(我就随意网上找了两张,伙伴们可自行PS,看起来美观一点)

2)toggle_selector.xml

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android" >
        <item android:state_checked="true" android:drawable="@drawable/on"></item>
        <item android:drawable="@drawable/off"></item>
    </selector>

3) 主布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.andy.androiduitogglebutton.MainActivity" >
         <ToggleButton
            android:id="@+id/togglebut1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/toggle_selector"
            android:textOn=""
            android:textOff=""
            android:checked="true">
         </ToggleButton>
</LinearLayout>

4) Java代码:

package com.andy.androiduitogglebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
	private ToggleButton togglebut1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//初始化togglebutton
		togglebut1 = (ToggleButton) findViewById(R.id.togglebut1);
		togglebut1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, Boolean isChecked) {
				if(isChecked){
					Toast.makeText(MainActivity.this, "打开", Toast.LENGTH_lONG).show();
				} else{
					Toast.makeText(MainActivity.this, "关闭", Toast.LENGTH_lONG).show();
				}
			}
		});
	}
}

4.2 java代码自定义可拖动ToggleButton

1)准备3张图片switch_btn_on.png(打开时背景图),switch_btn_off.png(关闭时背景图),switch_btn_slipper.png(滑块背景)

2)主布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.andy.androiduitogglebutton.MainActivity" >
            <com.andy.androiduitogglebutton.MyToggleButton 
                   android:id="@+id/my_togglebut"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"/>
</LinearLayout>

3)自定义View文件MyToggleButton.java

package com.andy.androiduitogglebutton;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class MyToggleButton extends View {
	//滑动開背景图片
	private  Bitmap toggle_bkg_on;
	//滑动關背景图片
	private  Bitmap toggle_bkg_off;
	//滑动块的图片
	private  Bitmap toggle_slip;
	//ToggleButton的状态
	private  Boolean toggleState=true;
	//滑动状态,false为未滑动状态
	private Boolean isSliding = false;
	//手指滑动的距离
	private float currentX;
	//声明OnToggleStateChangeListener接口变量
	private OnToggleStateChangeListener listener;
	public void setToggle_bkg_on(int toggle_bkg_on) {
		this.toggle_bkg_on = BitmapFactory.decodeResource(getResources(), toggle_bkg_on);
	}
	public void setToggle_bkg_off(int toggle_bkg_off) {
		this.toggle_bkg_off = BitmapFactory.decodeResource(getResources(), toggle_bkg_off);
	}
	public void setToggle_slip(int toggle_slip) {
		this.toggle_slip = BitmapFactory.decodeResource(getResources(), toggle_slip);
	}
	public void setToggleState(Boolean toggleState) {
		this.toggleState = toggleState;
	}
	/*帶3個參數構造方法,在xml中應用是可以指定樣式和屬性
        * context:上下文
        *AttributeSet:属性值集合
        *defStyleAttr:Theme下默认的Style
        */
	public MyToggleButton(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}
	/*
        * 帶2個參數構造方法,在xml中使用時可以指定屬性
        */
	public MyToggleButton(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	/*
        * 帶1個參數構造方法
        */
	public MyToggleButton(Context context) {
		super(context);
	}
	/*
        * 繼承View的方法,測量髖高
        */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
	}
	/*
        * 根据拖动位置绘制图像
        */
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		//如果移动距离小于背景一般,绘制关闭按钮背景,否则绘制打开按钮背景
		if (currentX <toggle_bkg_off.getWidth()/2){
			canvas.drawBitmap(toggle_bkg_off, 0, 0, null);
		} else{
			canvas.drawBitmap(toggle_bkg_on, 0, 0, null);
		}
		float slip_left = 0;
		if(isSliding){
			if(currentX > toggle_bkg_off.getWidth()-toggle_slip.getWidth()){
				slip_left = toggle_bkg_off.getWidth()-toggle_slip.getWidth();
				canvas.drawBitmap(toggle_slip, slip_left, 0,null);
			} else{
				slip_left = currentX - toggle_slip.getWidth()/2;
				canvas.drawBitmap(toggle_slip, slip_left, 0,null);
			}
		} else{
			if(toggleState){
				slip_left =toggle_bkg_off.getWidth() - toggle_slip.getWidth();
				canvas.drawBitmap(toggle_slip, slip_left, 0,null);
			} else{
				canvas.drawBitmap(toggle_slip, 0, 0,null);
			}
		}
		//滑出左边界
		if(currentX < 0){
			canvas.drawBitmap(toggle_slip, 0, 0,null);
		}
		//滑出右边界 
		if (currentX > toggle_bkg_off.getWidth()-toggle_slip.getWidth()){
			slip_left = toggle_bkg_off.getWidth()-toggle_slip.getWidth();
			canvas.drawBitmap(toggle_slip, slip_left, 0,null);
		}
	}
	/*
        * 继承view触摸事件方法并实现逻辑
        */
	@Override
	public Boolean onTouchEvent(MotionEvent event) {
		//获取滑动距离
		currentX = (int) event.getX();
		switch(event.getAction()){
			case MotionEvent.ACTION_DOWN:
			//滑动状态改成true
			currentX = event.getX();
			isSliding=true;
			break;
			case MotionEvent.ACTION_MOVE://移动
			currentX = event.getX();
			break;
			case MotionEvent.ACTION_UP:
			//滑动状态改成false
			isSliding=false;
			//如果滑动距离大于背景的1/2将开关打开,小于1/2将开关关闭
			if(currentX < toggle_bkg_off.getWidth()/2){
				//检测原来的开关状态是否为开,如果是开则关闭它
				if(toggleState){
					//关闭ToggleButton
					toggleState = false;
					//检测是否注册监听器,如果没有则注册
					if(listener != null){
						listener.onToggleStateChange(toggleState);
					}
				}
			} else{
				if(!toggleState){
					toggleState = true;
					//检测是否注册监听器,如果没有则注册
					if(listener !=null){
						listener.onToggleStateChange(toggleState);
					}
				}
			}
			break;
		}
		//在onTouchEvent事件完成后重新调用onDraw绘制图形
		invalidate();
		//返回true表示操作完毕
		return true;
	}
	/**
        * 定义一个ToggleButton状态改变监听器接口
        */
	interface OnToggleStateChangeListener{
		void onToggleStateChange(Boolean state);
	}
	/*
        *实现设置状态改变监听方法
        */
	public void setOnToggleStateChangeListener(OnToggleStateChangeListener listener){
		this.listener=listener;
	}
}

4)MainActivity.java

package com.andy.androiduitogglebutton;
import com.andy.androiduitogglebutton.MyToggleButton.OnToggleStateChangeListener;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
	private ToggleButton togglebutton;
	private MyToggleButton mytogglebutton;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//初始化mytogglebutton
		mytogglebutton =(MyToggleButton) findViewById(R.id.my_togglebut);
		//设置打开背景图
		mytogglebutton.setToggle_bkg_on(R.drawable.switch_btn_on);
		//设置关闭背景图
		mytogglebutton.setToggle_bkg_off(R.drawable.switch_btn_off);
		//设置滑动块背景图
		mytogglebutton.setToggle_slip(R.drawable.switch_btn_slipper);
		//设置ToggleButton初始状态
		mytogglebutton.setToggleState(false);
		//mytogglebutton设置监听
		mytogglebutton.setOnToggleStateChangeListener(new OnToggleStateChangeListener() {
			@Override
			public void onToggleStateChange(Boolean state) {
				if(state){
					Toast.makeText(MainActivity.this, "打开", Toast.LENGTH_sHORT).show();
				} else{
					Toast.makeText(MainActivity.this, "关闭", Toast.LENGTH_sHORT).show();
				}
			}
		});
	}
}
  • yiisaa
  • 这是我的微信扫一扫
  • weinxin
  • zhengweiqiangcom
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: