自定义view的简单操作

 
  
MainActivity里面的显示控件和方法自定义view的简单操作_第1张图片
package com.example.zidingyiview2;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.support.annotation. Nullable;
import android.util.AttributeSet;
import android.view.View; /** * Created by Administrator on 2018/3/11. */
public class ToggleButton extends View {

boolean state = false;
Bitmap buttonBackGroud ;
Bitmap buttonslidingBack;
//测量 -- 测量的模式,加上测量的大小 measure --- onmeasure setMeasuredDimension  
@Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);

setMeasuredDimension( buttonBackGroud.getWidth(), buttonBackGroud.getHeight());
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/** * 第一个参数是要画的图片  
* 第二个参数是离左边的距离
* 第三个参数是离顶部的距离  
* 第四个参娄是画笔  
*/  
canvas.drawBitmap( buttonBackGroud, 0, 0, null);
//画滑动块  
if ( state){
//是开的状态
canvas.drawBitmap( buttonslidingBack, buttonBackGroud.getWidth()- buttonslidingBack.getWidth(), 0, null
);
} else{
//关的状态 canvas.drawBitmap( buttonslidingBack, 0, 0, null);
}
}
public ToggleButton(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
/** * 开关的状态 true是开的状态 false是关的状态 */
public void setState( boolean flag) {
state = flag;
}
//开关的背影图片  
public void seButtonBackGround( int switch_background) {
buttonBackGroud = BitmapFactory. decodeResource(getResources(),switch_background);
}
//滑动块的背景图片
public void setSlidingBack( int slide_button_background) {
buttonslidingBack = BitmapFactory. decodeResource(getResources(),slide_button_background);
}
}

你可能感兴趣的:(自定义view的简单操作)