Android开发-自定义view-简化版自定义开关

来源:互联网 发布:wwe2k16优化 编辑:程序博客网 时间:2024/05/22 02:22

趁工作不忙的时候写了一个小demo,一个简单的自定义开关,开关基本的功能都具备(除了on/off好像也没什么其他功能)。

下面看代码:

首先创建attrs文件(res/values/):

<?xml version="1.0" encoding="utf-8"?>
<resources>  
    <declare-styleable name="kurtswitch">
        <attr name="onBgColor" format="reference|color" />
        <attr name="offBgColor" format="reference|color" />
        <attr name="thumbColor" format="reference|color" />
    </declare-styleable>
</resources>

接下来创建java文件开始写view,流程很简单,代码中都有注释,会一点编程的基本都可以看懂:

public class KurtOnOff extends View implements OnGestureListener {
private  boolean ON = true;
private int OnBgColor;
private int OffBgColor;
private int ThumbColor;//滑动按钮的颜色
private Paint paint = new Paint();
private boolean IsScolling = false;//滚动状态
private GestureDetector mGestureDetector;
private int ThumbLeft = 0;
private KurtSwitchListener MyKurtSwitchLisener;//控件状态改变的监听
public KurtOnOff(Context context) {
this(context,null);
}
public KurtOnOff(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public KurtOnOff(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//初始化手势类
mGestureDetector = new GestureDetector(this);
//获取自定义属性值
TypedArray a = getContext().obtainStyledAttributes(attrs,
R.styleable.kurtswitch);
OnBgColor = a.getColor(R.styleable.kurtswitch_onBgColor, Color.RED);
OffBgColor = a.getColor(R.styleable.kurtswitch_offBgColor, Color.GRAY);
ThumbColor = a.getColor(R.styleable.kurtswitch_thumbColor, Color.GREEN);
//別忘了执行这一句
a.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制背景
DrawBackGround(canvas);
//绘制滑动按钮
DrawThumb(canvas);
}
private void DrawBackGround(Canvas canvas) {
//在不滑动状态下
if (!IsScolling) {
//如果是开启状态,旋钮放在最左边,否则放在右边
if (ON) {
ThumbLeft = 0;
} else {
ThumbLeft = getWidth() - getHeight();
}

paint.setAntiAlias(true);
paint.setColor(OffBgColor);
// 左半拉
RectF rect = new RectF(0, 0, ThumbLeft + getHeight(), getHeight());
canvas.drawRoundRect(rect, getHeight() / 2, getHeight() / 2, paint);
// -----------------------------------------------------------------------------------------------
paint.setColor(OnBgColor);
// 右半拉
RectF rect1 = new RectF(ThumbLeft, 0, getWidth(), getHeight());
canvas.drawRoundRect(rect1, getHeight() / 2, getHeight() / 2, paint);
}
private void DrawThumb(Canvas canvas) {
// TODO Auto-generated method stub
paint.setAntiAlias(true);
paint.setColor(ThumbColor);
RectF rect = new RectF();
if (IsScolling) {
rect.left = ThumbLeft;
} else {
if (ON) {
ThumbLeft = 0;
} else {
ThumbLeft = getWidth() - getHeight();
}
rect.left = this.ThumbLeft;
}


rect.top = 0;
rect.right = this.ThumbLeft + getHeight();
rect.bottom = getHeight();
canvas.drawArc(rect, 0, 360, false, paint);
}


@Override
public boolean onTouchEvent(MotionEvent event) {
try {
mGestureDetector.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP) {
MyUpEvent();
}
} catch (Exception e) {
// TODO: handle exception
}
return true;
}
//手势抬起事件
private void MyUpEvent() {
IsScolling = false;
boolean oldOn = ON;
if (ThumbLeft < getWidth() / 2) {
ON = true;
ThumbLeft = 0;
} else {
ON = false;
ThumbLeft = getWidth() - getHeight();
}
this.invalidate();
// 如果监听不为空切 oldOn和现在的on 状态不一样 说明状态发生改变,调用监听
if (MyKurtSwitchLisener != null && oldOn != ON) {
MyKurtSwitchLisener.onSwitchChangeListener(this, ON);
}
}
@Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
//滑动状态
IsScolling = true;
ThumbLeft = (int) e2.getX();
if (ThumbLeft > (getWidth() - getHeight())) {
ThumbLeft = (getWidth() - getHeight());
}
if (ThumbLeft < 0) {
ThumbLeft = 0;
}
invalidate();
return false;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
return false;
}
public void setonKurtSwitchListener(KurtSwitchListener MyKurtSwitchLisener) {
this.MyKurtSwitchLisener = MyKurtSwitchLisener;
}
//设置状态
public void setStatus(boolean status){
this.ON=status;
if(ON){
ThumbLeft=0;
}else{
ThumbLeft=getWidth()-getHeight();
}
this.invalidate();
}
public interface KurtSwitchListener {
public void onSwitchChangeListener(View view, boolean status);
}
}

ok,到此为止,控件就写好了,接下来使用它。

在mainactivity布局文件中调用它:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res/com.example.kurtswitch"       这句切记配置。res/后面的是工程包名
    android:id="@+id/rel"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.kurtswitch.KurtActivity" >
    <com.example.kurtswitch.KurtOnOff
        android:id="@+id/swit"
        android:layout_width="300dp"
        android:layout_height="40dp" />
    <com.example.kurtswitch.KurtOnOff
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:layout_below="@+id/swit"
        android:layout_marginTop="10dp"
        app:offBgColor="#550000aa"
        app:onBgColor="#aaaa00"
        app:thumbColor="#fff" />
</RelativeLayout>

这样运行就已经可以看到结果了。

mainactivity中再写一下测试监听和控制状态的方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kurt);
KurtOnOff o = (KurtOnOff) findViewById(R.id.swit);
o.setStatus(false);
o.setonKurtSwitchListener(new KurtSwitchListener() {


@Override
public void onSwitchChangeListener(View view, boolean status) {
// TODO Auto-generated method stub
Log.e("Kurt", "===>" + status);
Toast.makeText(KurtActivity.this, "==>" + status,
Toast.LENGTH_SHORT).show();
}
});
}

就这些。ok,大功告成,亲个嘴吧。


0 0
原创粉丝点击