自定义View解析

首先我们先介绍组合View:
public class MyXHView extends LinearLayout {
private EditText mEditText;
private TextView mCancel;

public MyXHView(Context context, AttributeSet attrs) {
    super(context, attrs);
    LayoutInflater.from(context).inflate(R.layout.header_view, this);
    mEditText = findViewById(R.id.Search_Edit);
    mCancel = findViewById(R.id.Cancel_Text);
}

public String getEditStr() {
    return mEditText.getText().toString();
}

public TextView getmCancel() {
    return mCancel;
}

}

ball:
public class BallView extends View {

private Paint paint;
Context context;

//圆的初始位置坐标
private int x = 38;
private int y = 38;
private int radius = 35;    //圆半径

public BallView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
}

/**
 * 实现onDraw()方法实现绘图操作
 *
 * @param canvas
 */
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    //用canvas将屏幕设为白色
    canvas.drawColor(Color.WHITE);

    //设置画笔颜色为红色
    paint = new Paint();
    paint.setColor(Color.RED);

    //设置消除锯齿
    paint.setAntiAlias(true);
    //使用画笔绘制圆为小球
    //x :圆心的x坐标
    //y :圆心的y坐标
    //radius :圆的半径
    //paint :画笔
    canvas.drawCircle(x, y, radius, paint);
}

//实现onTouchEvent方法,处理触摸事件
@Override
public boolean onTouchEvent(MotionEvent event) {
    //判断触摸点
    switch (event.getAction()) {
        //实现MotionEvent.ACTION_DOWN,记录按下的x,y坐标:getRawX()和getRawY()获得的是相对屏幕的位置
        case MotionEvent.ACTION_DOWN:
            x = (int) event.getX();
            y = (int) event.getY();
            System.out.println("按下时:  " + "x坐标:" + event.getRawX() + "     " + "y坐标:" + event.getRawY());

            //实现MotionEvent.ACTION_MOVE 记录移动的x,y坐标:getRawX()和getRawY()获得的是相对屏幕的位置
        case MotionEvent.ACTION_MOVE:
            x = (int) event.getX();
            y = (int) event.getY();
            System.out.println("移动时:  " + "x坐标:" + event.getRawX() + "     " + "y坐标:" + event.getRawY());

            //实现MotionEvent.ACTION_UP 记录抬起的x,y坐标
        case MotionEvent.ACTION_UP:
            // 获取当前触摸点的x,y坐标,为X轴和Y轴坐标重新赋值:getX()和getY()获得的永远是view的触摸位置坐标
            x = (int) event.getX();
            y = (int) event.getY();
            System.out.println("抬起时:  " + "x坐标:" + event.getRawX() + "     " + "y坐标:" + event.getRawY());
            break;
    }

    //获取屏幕宽高
    WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    int width = manager.getDefaultDisplay().getWidth();
    int height = manager.getDefaultDisplay().getHeight();

    //修正圆点坐标,重新绘制圆 ,控制小球不会被移出屏幕
    if (x >= 18 && y >= 18 && x <= width - 18 && y <= height - 18) {
        /**
         *  Android提供了Invalidate方法实现界面刷新,但是Invalidate不能直接在线程中调用,因为他是违背了单线程模型:
         1. Android UI操作并不是线程安全的,并且这些操作必须在UI线程中调用。
            invalidate()是用来刷新View的,必须是在UI线程中进行工作。比如在修改某个view的显示时,调用invalidate()才能看到重新绘制的界面。invalidate()的调用是把之前的旧的view从主UI线程队列中pop掉。
         2.Android 程序默认情况下也只有一个进程,但一个进程下却可以有许多个线程。在这么多线程当中,把主要是负责控
         制UI界面的显示、更新和控件交互的线程称为UI线程,由于onCreate()方法是由UI线程执行的,所以也可以把UI线程理解
         为主线程。其余的线程可以理解为工作者线程。invalidate()得在UI线程中被调动,在工作者线程中可以通过Handler来通
         知UI线程进行界面更新。而postInvalidate()在工作者线程中被调用。
         */
        //使用 postInvalidate()方法实现重绘小球,跟随手指移动

// postInvalidate();
postInvalidate();
}
/*
* 备注:此处一定要将return super.onTouchEvent(event)修改为return true,原因是:
* 1)父类的onTouchEvent(event)方法可能没有做任何处理,但是返回了false。
* 2)一旦返回false,在该方法中再也不会收到MotionEvent.ACTION_MOVE及MotionEvent.ACTION_UP事件。
*/
//return super.onTouchEvent(event);
return true;
}

}
每点击一次+1:

public class CounterView extends View implements View.OnClickListener {
private Paint mPaint;
private Rect mRect;
// 计数值,每点击一次本控件,其值增加1
private int mCount;

public CounterView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mPaint = new Paint();
    mRect = new Rect();
    setOnClickListener(this);
}


@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mPaint.setColor(Color.RED);
    canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
    String text = String.valueOf(mCount);
    mPaint.setColor(Color.YELLOW);
    mPaint.setTextSize(50);
    mPaint.getTextBounds(text, 0, text.length(), mRect);
    int width = mRect.width();
    int height = mRect.height();
    canvas.drawText(text, getWidth() / 2 - width / 2, getHeight() / 2 + height / 2, mPaint);
    Log.e("getWidth", getWidth() + "");
    Log.e("getHeight", getHeight() + "");
    Log.e("height", height + "");

}

@Override
public void onClick(View v) {
    mCount++;
    invalidate();
}

}
画环画圆 myView:
先在values建立xml文件:

<?xml version="1.0" encoding="utf-8"?>
    <attr name="textSize" format="dimension" />
    <attr name="text" format="string" />
    <attr name="circleColor" format="color" />
    <attr name="arcColor" format="color" />
    <attr name="textColor" format="color" />
    <attr name="startAngle" format="integer" />
    <attr name="sweepAngle" format="integer" />
</declare-styleable>
然后在布局中:
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:startAngle="0"
    app:sweepAngle="270"
    app:text="hehe"
    app:textSize="30sp"
    app:textColor="@color/colorPrimaryDark"
    app:circleColor="@color/colorPrimary"
    app:arcColor="@color/colorAccent"
  • 自己在value文件夹下新建attrs文件 就可以在它里面定义自己想要的属性了
  • 咱们自定义View初始化的东西要放到构造函数之后执行
  • 因为我们自己写的View执行顺序
  • 1:构造方法
  • 2:测量

*/
public class MyView extends View {

private String text;
private int circleColor;
private int arcColor;
private int textColor;
private float textSize;
private int startAngle;
private int sweepAngle;
private int mCircleXY;
private float mRadius;
private Paint mCirclePaint;
private RectF mRectF;
private Paint mArcPaint;
private Paint mTextPaint;

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    //得到我们自己定义的属性集合
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyView);
    if (ta != null) {
        //两个参数  参数1:R.styleable.MyView_circleColor 代表的咱们自己定义属性集合
        //参数2:如果你在布局文件里面没有添加定义的属性 就给一个默认值
        circleColor = ta.getColor(R.styleable.MyView_circleColor, 0);
        arcColor = ta.getColor(R.styleable.MyView_arcColor, 0);
        textColor = ta.getColor(R.styleable.MyView_textColor, 0);
        textSize = ta.getDimension(R.styleable.MyView_textSize, 50);
        text = ta.getString(R.styleable.MyView_text);
        startAngle = ta.getInt(R.styleable.MyView_startAngle, 0);
        sweepAngle = ta.getInt(R.styleable.MyView_sweepAngle, 90);
        ta.recycle();
        Log.e("text", text);
    }
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    drawSth(canvas);
}

private void drawSth(Canvas canvas) {
    init();
    canvas.drawCircle(mCircleXY, mCircleXY, mRadius, mCirclePaint);
    canvas.drawArc(mRectF, startAngle, sweepAngle, false, mArcPaint);
    canvas.drawText(text, 0, text.length(), mCircleXY, mCircleXY + textSize
            / 4, mTextPaint);
}

private void init() {
    //getWidth() 得到当前这个空间宽和高
    int length = Math.min(getWidth(), getHeight());
    Log.e("看看宽和高", "宽度:" + getWidth() + "高度:" + getHeight());
    mCircleXY = length / 2;
    mRadius = length * 0.5f / 2;
    mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mCirclePaint.setColor(circleColor);
    mRectF = new RectF(length * 0.1f, length * 0.1f, length * 0.9f,
            length * 0.9f);

    mArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mArcPaint.setColor(arcColor);
    mArcPaint.setStyle(Paint.Style.STROKE);
    mArcPaint.setStrokeWidth((getWidth() * 0.1f));

    mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mTextPaint.setTextSize(textSize);
    mTextPaint.setColor(textColor);
    mTextPaint.setTextAlign(Paint.Align.CENTER);

}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Log.e("onMeasure", "onMeasure");
}

}

猜你喜欢

转载自blog.csdn.net/wangyonghao132/article/details/84609485