1、自定义view,背景和开关的绘制
package view;
import com.example.selftoggle.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class SwichToggle extends View {
private Paint mPaint;
private boolean mIstoggleon = false;
private float mScaleNum = 0.5f;
private Bitmap mNewBack_bt;
private Bitmap mNewSwitchto;
//构造方法
public SwichToggle(Context context, AttributeSet attrs) {
super(context, attrs);
//初始化drawable图片
Bitmap mBack_bt = BitmapFactory.decodeResource(getResources(), R.drawable.switch_background);
Bitmap mSwithcto = BitmapFactory.decodeResource(getResources(), R.drawable.switch_button);
mPaint = new Paint();
mNewBack_bt = scaleBitmap(mBack_bt, mScaleNum);
mNewSwitchto = scaleBitmap(mSwithcto, mScaleNum);
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mIstoggleon=!mIstoggleon;
invalidate();
if (mListener != null) {
mListener.setIstoggleOnOrNot(mIstoggleon);
}
}
});
}
//重写测量的方法
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 根据图片的高度来设置高度和宽度
setMeasuredDimension(mNewBack_bt.getWidth(), mNewBack_bt.getHeight());
}
@Override
protected void onDraw(Canvas canvas) {
// 画背景
canvas.drawBitmap(mNewBack_bt, 0, 0, mPaint);
//画开关
if (mIstoggleon) {
canvas.drawBitmap(mNewSwitchto, mNewBack_bt.getWidth()-mNewSwitchto.getWidth(), 0, mPaint);
}else {
canvas.drawBitmap(mNewSwitchto, 0, 0, mPaint);
}
}
// 接口回调来传递开关的状态
private setIstoggleOnLister mListener;
public interface setIstoggleOnLister{
void setIstoggleOnOrNot(boolean istoggleon);
}
public void setIstoggleOnLister(setIstoggleOnLister listener){
mListener = listener;
}
//缩放bitmap的方法
private Bitmap scaleBitmap(Bitmap bitmap,float scaleNum) {
Matrix matrix = new Matrix();
matrix.postScale(scaleNum,scaleNum);
Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
return resizeBmp;
}
}
2、布局的引用:
<view.SwichToggle
android:id="@+id/iv_toggle"
android:layout_width="20dp"
android:layout_height="20dp"
/>
3、activity中的引用:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIs_toggle = (SwichToggle) findViewById(R.id.iv_toggle);
initListener();
}
private void initListener() {
// TODO Auto-generated method stub
mIs_toggle.setIstoggleOnLister(new setIstoggleOnLister() {
@Override
public void setIstoggleOnOrNot(boolean istoggleon) {
if (istoggleon) {
Toast.makeText(MainActivity.this, "关闭了", 1).show();
}else {
Toast.makeText(MainActivity.this, “打开了”,1).show();
}
}
});
}