自定义开关:
用我自己的话来讲:自定义控件就是自己绘制图像展示呈控件--但有根据用户的操作的控件必须跟随着绘制新图像并展示控件
public class ToggleView extends View {
private Bitmap switchBackGround;
private Bitmap slideButtonBackGround;
private boolean currentState=false;
private int currentX=0;
private boolean isMove=false;
private onToggleStateChangeListener lt;
public ToggleView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.ToggleView);
int count=array.getIndexCount();
for(int i=0;i<count;i++){
int index=array.getIndex(i);
switch(index){
case R.styleable.ToggleView_Switchbackground:
setSwitchbackground(array.getInt(index, -1));
break;
case R.styleable.ToggleView_slidebackground:
setslidebackground(array.getInt(index, -1));
break;
case R.styleable.ToggleView_currentState:
setcurrentState(array.getBoolean(index, false));
break;
default:
break;
}
}
}
public void setSwitchbackground(int switchBackground) {
switchBackGround = BitmapFactory.decodeResource(getResources(), switchBackground);
}
public void setslidebackground(int slideButtonBackground) {
// TODO Auto-generated method stub
slideButtonBackGround=BitmapFactory.decodeResource(getResources(), slideButtonBackground);
}
public void setcurrentState(boolean b) {
// TODO Auto-generated method stub
currentState=b;
}
@Override
protected void onDraw(Canvas canvas) {
//将背景图片画到面板上
canvas.drawBitmap(switchBackGround, 0, 0, null);
//将开关按钮背景图片画到画板上
if(isMove){
int left=currentX-slideButtonBackGround.getWidth()/2;
if(left<0){
left=0;
}else if(left>switchBackGround.getWidth()-slideButtonBackGround.getWidth()){
left=switchBackGround.getWidth()-slideButtonBackGround.getWidth();
}
canvas.drawBitmap(slideButtonBackGround, left, 0, null);
}else{
if(currentState){
canvas.drawBitmap(slideButtonBackGround, switchBackGround.getWidth()-slideButtonBackGround.getWidth(), 0, null);
}else{
canvas.drawBitmap(slideButtonBackGround, 0, 0, null);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(switchBackGround.getWidth(), switchBackGround.getHeight());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
//获取现在中心点
currentX = (int) event.getX();
isMove=true;
break;
case MotionEvent.ACTION_MOVE:
currentX=(int) event.getX();
break;
case MotionEvent.ACTION_UP:
isMove = false;
currentX=(int) event.getX();
boolean result=currentX>switchBackGround.getWidth()/2;
if(currentState!=result&<!=null){
lt.changeState(result);
}
currentState=result;
break;
};
invalidate();
return true;
}
/**
*
* @param listener
*/
public void setonToggleStateChangeListener(onToggleStateChangeListener listener){
lt = listener;
}