您的位置:首页 > 移动开发 > Android开发

Android自定义View——开关按钮SwitchButton

2016-05-02 23:39 721 查看
在coding的过程中需要用到简单的switch-button,因为Android自带库没有此组件,使用就打算自定义view实现一个开关按钮。
我使用了view的组合,首先思考开关按钮的组成,分为2个部分,一个是底部的圆角矩形,一部分是在开关过程中变换位置的圆。
于是写出按钮的xml布局


layout_switch.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout_bg"
android:layout_width="64dp"
android:layout_height="32dp"
android:background="@drawable/bg_switch_bottom_open">

<View
android:id="@+id/view_scroll"
android:layout_width="32dp"
android:layout_height="32dp"
android:background="@drawable/bg_switch_top_open"/>

</RelativeLayout>


分别为2部分写背景的资源文件

底部部分在开关2种状态下的布局文件分别为bg_switch_botttom_open.xml和bg_switch_bottom.xml文件

2个布局文件的代码分别如下所示:

bg.switch_bottom_open.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="@android:color/holo_red_dark" />
<corners android:radius="32dp" />
<solid android:color="@android:color/holo_red_light" />
</shape>


bg_bottom_bottom.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="@android:color/darker_gray" />
<corners android:radius="32dp" />
<solid android:color="@android:color/darker_gray" />
</shape>


同理,上方的圆圈的背景资源文件也分为bg_switch_top_open.xml和bg_switch_top.xml2个

具体代码如下:

bg_switch_top_open.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="1dp"
android:color="@android:color/holo_red_dark" />
<corners android:radius="8dp" />
<size
android:width="30dp"
android:height="30dp" />
<solid android:color="@android:color/white"/>
</shape>


bg_switch_top.xml代码:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="1dp"
android:color="@android:color/darker_gray" />
<corners android:radius="8dp" />
<size
android:width="30dp"
android:height="30dp" />
<solid android:color="@android:color/white"/>
</shape>


接下来,我们给SwitchButton自定义一个属性,defaultStatus,即默认属性,即应用启动的时候该按钮的默认状态,分为open和close。
在res/values目录下新建attrs.xml文件,代码如下:


<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SwitchButton">
<attr name="defaultStatus">
<enum name="open" value="1"/>
<enum name="close" value="0"/>
</attr>
</declare-styleable>
</resources>


接着,就可以在java代码中定义我们的SwitchButton组件

新建一个类SwitchButton.java和一个接口OnSwitchListener.java

借口的代码如下:

/**
* Created by chenglei on 2016/5/2.
* 开关监听的接口
*/
public interface OnSwitchListener {
void onSwitchChange();
}


SwitchButton.java的代码如下:


public class SwitchButton extends RelativeLayout {

public static final int OPEN = 1;   //状态开
public static final int CLOSE = 0;   //状态关

private int defaultStatus;   //默认状态

private int currentStatus;     //当前状态
private OnSwitchListener onSwitchListener;   //状态变化接口

private TypedArray typedArray;  //自定义属性数组

private RelativeLayout relativeLayout;   //相对布局,代表按钮的下面一部分
private View view;  //view,代表上方的圆形部分

public SwitchButton(Context context) {
super(context);
}

public SwitchButton(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.layout_switch, this);   //实现布局
typedArray = context.obtainStyledAttributes(attrs, R.styleable.SwitchButton);   //获取自定义属性
initView();   //初始化视图和控件
init();       //初始化按钮的状态
}
}


下面,我们分别实现initView和init2个方法

在initView方法中,我们需实例化控件

relativeLayout = (RelativeLayout)findViewById(R.id.relative_layout_bg);

view = findViewById(R.id.view_scroll);


在init方法中,我们需要初始化按钮的开关状态

首先从自定义的属性中获取默认的开关状态,如果没有定义,则默认为1(开启状态)

defaultStatus = typedArray.getInt(R.styleable.SwitchButton_defaultStatus, 1);


然后根据默认状态设置当前状态,并且设定没种情况下的布局

if (defaultStatus == 0) {
relativeLayout.setBackgroundResource(R.drawable.bg_switch_bottom);
view.setBackgroundResource(R.drawable.bg_switch_top);
setViewLocation(view, RelativeLayout.ALIGN_PARENT_LEFT);
currentStatus = CLOSE;
} else if (defaultStatus == 1) {
relativeLayout.setBackgroundResource(R.drawable.bg_switch_bottom_open);
view.setBackgroundResource(R.drawable.bg_switch_top_open);
setViewLocation(view, RelativeLayout.ALIGN_PARENT_RIGHT);  //设置圆形部分的位置
currentStatus = OPEN;
}


开关状态的过程,为了简单起见,我们使用的是改变它的位置,在开启状态下,默认圆圈部分在相对布局的最右边,在关闭状态的时候,默认圆圈部分在相对布局的最左边

我们编写setViewLocation方法:

LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();  //获取view的布局参数
/**
*  将当前需要设置的布局的相反设置从参数设置中去除
*  在开启状态的时候,圆形部分在最右侧,将按钮切换为关闭状态的时候
*  如果不把view在父布局最右侧这一属性去掉,会导致ALIGN_PARENT_LEF
*  T和ALIGN_PARENT_RIGHT属性同时设置
*  导致布局出现错误
*/
if (location == RelativeLayout.ALIGN_PARENT_LEFT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
} else if (location == RelativeLayout.ALIGN_PARENT_RIGHT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
}
}
layoutParams.addRule(location);
view.setLayoutParams(layoutParams);


下面来编写具体的开关切换,重写onTouchEvent方法,在DOWN事件触发的时候就改变状态

case MotionEvent.ACTION_DOWN:
/**
* 改变状态
*/
changeStatus();
break;


编写状态改变方法changeStatus

if (currentStatus == OPEN) {
closeButton();
} else if (currentStatus == CLOSE) {
openButton();
}
if (onSwitchListener != null) {
onSwitchListener.onSwitchChange();  //调用监听改变时候处理逻辑的函数
}


在下面编写closeButton和openButton的逻辑:

/**
* 关闭按钮
*/
private void closeButton() {
relativeLayout.setBackgroundResource(R.drawable.bg_switch_bottom);
view.setBackgroundResource(R.drawable.bg_switch_top);
setViewLocation(view, RelativeLayout.ALIGN_PARENT_LEFT);
currentStatus = CLOSE;
}

/**
* 打开按钮
*/
private void openButton() {
relativeLayout.setBackgroundResource(R.drawable.bg_switch_bottom_open);
view.setBackgroundResource(R.drawable.bg_switch_top_open);
setViewLocation(view, RelativeLayout.ALIGN_PARENT_RIGHT);
currentStatus = OPEN;
}


可以注意到,在changeStatus方法中我们加入了如下语句:

if (onSwitchListener != null) {
onSwitchListener.onSwitchChange();  //调用监听改变时候处理逻辑的函数
}


这是为了在此类的调用处,设置监听器并进行回调

所以,我们还需要在SwitchButton类中添加监听设置方法

如下:

public void setOnSwitchListener(OnSwitchListener onSwitchListener) {
this.onSwitchListener = onSwitchListener;
}


在此,我们的代码就基本写完了,我们看看这个自定义如何使用

在MainActivity的布局文件activity_main.xml文件中添加布局:

<com.switchbutton.SwitchButton
android:id="@+id/switch_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:defaultStatus="open"></com.switchbutton.SwitchButton>


在MainActivity中实例化控件:

switchButton = (SwitchButton) findViewById(R.id.switch_button);


设置OnSwitchListener监听并实现回调方法,具体过程如下:

switchButton.setOnSwitchListener(new OnSwitchListener() {
@Override
public void onSwitchChange() {
Toast.make(MainActivity.class, "状态改变", Toast.LENGTH_SHORT).show();
}
});


运行效果如图:



完整的代码如下所示,供大家参考

demo过程文件已经提交至github,地址:https://github.com/wsclwps123/switchButton

谢谢大家支持!

package com.switchbutton;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

/**
* Created by chenglei on 2016/5/2.
* 自定义开关按钮
*/
public class SwitchButton extends RelativeLayout {

public static final int OPEN = 1;
public static final int CLOSE = 0;

private int defaultStatus;

private int currentStatus;
private OnSwitchListener onSwitchListener;

private TypedArray typedArray;

private RelativeLayout relativeLayout;
private View view;

public SwitchButton(Context context) {
super(context);
}

public SwitchButton(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.layout_switch, this);
typedArray = context.obtainStyledAttributes(attrs, R.styleable.SwitchButton);
initView();
init();
}

/**
* 初始化控件
*/
private void initView() {
relativeLayout = (RelativeLayout) findViewById(R.id.relative_layout_bg);
view = findViewById(R.id.view_scroll);
}

/**
* 初始化操作
*/
private void init() {
defaultStatus = typedArray.getInt(R.styleable.SwitchButton_defaultStatus, 1);
if (defaultStatus == 0) {
relativeLayout.setBackgroundResource(R.drawable.bg_switch_bottom);
view.setBackgroundResource(R.drawable.bg_switch_top);
setViewLocation(view, RelativeLayout.ALIGN_PARENT_LEFT);
currentStatus = CLOSE;
} else if (defaultStatus == 1) {
relativeLayout.setBackgroundResource(R.drawable.bg_switch_bottom_open);
view.setBackgroundResource(R.drawable.bg_switch_top_open);
setViewLocation(view, RelativeLayout.ALIGN_PARENT_RIGHT);
currentStatus = OPEN;
}
}

private void setViewLocation(View view, int location) {
LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
if (location == RelativeLayout.ALIGN_PARENT_LEFT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
} else if (location == RelativeLayout.ALIGN_PARENT_RIGHT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
}
}
layoutParams.addRule(location);
view.setLayoutParams(layoutParams);
}

/**
* 获取当前的状态
*/
public int getCurrentStatus() {
return currentStatus;
}

/**
* 设置状态变化监听
*/
public void setOnSwitchListener(OnSwitchListener onSwitchListener) { this.onSwitchListener = onSwitchListener; }

/** * 关闭按钮 */ private void closeButton() { relativeLayout.setBackgroundResource(R.drawable.bg_switch_bottom); view.setBackgroundResource(R.drawable.bg_switch_top); setViewLocation(view, RelativeLayout.ALIGN_PARENT_LEFT); currentStatus = CLOSE; } /** * 打开按钮 */ private void openButton() { relativeLayout.setBackgroundResource(R.drawable.bg_switch_bottom_open); view.setBackgroundResource(R.drawable.bg_switch_top_open); setViewLocation(view, RelativeLayout.ALIGN_PARENT_RIGHT); currentStatus = OPEN; }

/**
* 改变状态
*/
private void changeStatus() {
if (currentStatus == OPEN) { closeButton(); } else if (currentStatus == CLOSE) { openButton(); } if (onSwitchListener != null) { onSwitchListener.onSwitchChange(); //调用监听改变时候处理逻辑的函数 }
}

/**
* 触摸事件
* 触摸一下,改变按钮的状态
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: /** * 改变状态 */ changeStatus(); break;
default:
break;
}
return super.onTouchEvent(event);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android