上次讲的自定义控件刷新点屏幕的任意地方都会刷新,而且在xml里自定义控件下面放一个textview的话,这个TextView是显示不出来的,不只这个,以前的几个自定义控件都是
为什么呢?今天来讲下onMeasure()
在自定义刷新控件的基础上重写onMeasure方法
根据上一篇自定义组件修改
注释在代码里
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- >
- <xue.test.CusView3
- android:id="@+id/cusview3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- </xue.test.CusView3>
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="我终于出现了" />
- </LinearLayout>
这里的TextView无法显示,想要显示的话,要测量控件的大小
- public class CusView3 extends View {
-
- private int color = 0;
- private String text = "点击我刷新";
- private Paint mPaint;
- private int mAscent;
-
- public CusView3(Context context, AttributeSet attrs) {
- super(context, attrs);
- mPaint = new Paint();
- mPaint.setStyle(Style.FILL);
- mPaint.setTextSize(35.0f);
- setPadding(20, 60, 0, 0);
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- if (color > 2) {
- color = 0;
- }
- switch (color) {
- case 0:
- mPaint.setColor(Color.GREEN);
- break;
- case 1:
- mPaint.setColor(Color.RED);
- break;
- case 2:
- mPaint.setColor(Color.BLUE);
- break;
-
- default:
- break;
- }
-
- canvas.drawText(text, getPaddingLeft(), getPaddingTop(), mPaint);
- }
-
- public void changeColor() {
- color++;
- }
-
-
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
- }
-
- private int measureWidth(int measureSpec) {
- int result = 0;
- int specMode = MeasureSpec.getMode(measureSpec);
- int specSize = MeasureSpec.getSize(measureSpec);
-
- if (specMode == MeasureSpec.EXACTLY) {
-
- result = specSize;
- } else {
-
- result = (int) mPaint.measureText(text) + getPaddingLeft() + getPaddingRight();
- if (specMode == MeasureSpec.AT_MOST) {
-
-
- result = Math.min(result, specSize);
- }
- }
-
- return result;
- }
-
- private int measureHeight(int measureSpec) {
- int result = 0;
- int specMode = MeasureSpec.getMode(measureSpec);
- int specSize = MeasureSpec.getSize(measureSpec);
-
- mAscent = (int) mPaint.ascent();
- if (specMode == MeasureSpec.EXACTLY) {
-
- result = specSize;
- } else {
-
- result = (int) (-mAscent + mPaint.descent()) + getPaddingTop() + getPaddingBottom();
- if (specMode == MeasureSpec.AT_MOST) {
-
-
- result = Math.min(result, specSize);
- }
- }
- return result;
- }
- }
效果图

代码 http://download.csdn.net/detail/ethan_xue/4178423
android自定义控件 onMeasure() 测量尺寸
原文:http://www.cnblogs.com/Free-Thinker/p/4508007.html