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

android 自定义View drawable

2015-07-23 19:17 761 查看
先看效果图:



自定义的步骤:

1.自定义view的属性

2.获取view的属性

3.设置view的高和宽

4.重绘view

1、在values文件平下新attr.xml文件,内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="customTv">
<attr name="img" format="reference"/>
<attr name="textBg" format="reference"/>
</declare-styleable>
</resources>


2、在自定义view获取v自定义属性

/**左边的icon*/
private Bitmap mImg;
/**引用的drawable selector*/
private Drawable mDrawable;
/**View 宽*/
private int mWidth;
/**View 高*/
private int mHeight;
/**画笔*/
private Paint mPaint;

public CustomTextView(Context context) {
this(context, null);
}

public CustomTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context,attrs,defStyle);
}

private void initView(Context context, AttributeSet attrs, int defStyle) {
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.customTv,defStyle,0);
int n = a.getIndexCount();
for(int i = 0; i < n; i++){
int attr = a.getIndex(i);
switch (attr){
case R.styleable.customTv_img:
mImg = BitmapFactory.decodeResource(getResources(),a.getResourceId(attr,0));
break;
case R.styleable.customTv_textBg:
mDrawable = a.getDrawable(attr);
break;
}
}
a.recycle();
mPaint = new Paint();
updateDrawable(mDrawable);
}

/**
* 设置要改变drawable
* @param d
*/
private void updateDrawable(Drawable d) {
d.setCallback(this);
drawableStateChanged();
invalidate();
}

@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
Drawable d = mDrawable;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
}


2、View 的高和宽

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mWidth = mImg.getWidth() + mDrawable.getIntrinsicWidth();
mHeight = mImg.getHeight();
setMeasuredDimension(mWidth,mHeight);
}


4、绘制View

@Override
protected void onDraw(Canvas canvas) {
/**绘制左边的Icon*/
canvas.drawBitmap(mImg, 0f, 0f, mPaint);
/**设置drawable范围*/
mDrawable.setBounds(0,0,mDrawable.getIntrinsicWidth(),mDrawable.getIntrinsicHeight());
/**画布右移50*/
canvas.translate(50,0);
/**绘制drawable*/
mDrawable.draw(canvas);
}


只有右边的才有点击效果,左边的icon不需要点击交果,重写onTouchEvent()

@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
/**点击的坐标左边icon范围内,消费此次事件*/
if((int)event.getX() < mImg.getWidth())
return false;
break;
}
return super.onTouchEvent(event);
}


源码地址:http://download.csdn.net/detail/ooppcool/8927453
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: