1>定义继承View的子类,根据业务需求重写View的方法
package com.brady.view; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.MotionEvent; import android.view.View; @SuppressLint("ClickableViewAccessibility") public class DrawView extends View { //半径 private int radius = 15; private float currentX = 25; private float currentY = 25; //创建画笔 private Paint paint = new Paint(); public DrawView(Context context) { super(context); } @Override public boolean onTouchEvent(MotionEvent event) { currentX = event.getX(); currentY = event.getY(); //使整个View实现,如果View可见,则onDraw会被调用 //This must be called from a UI thread. To call from a non-UI thread, call postInvalidate(). invalidate(); return true; } @Override protected void onDraw(Canvas canvas) { paint.setColor(Color.RED); canvas.drawCircle(currentX, currentY, radius, paint); super.onDraw(canvas); } }
引用该子类方式:
1>直接实例化添加
2>在xml中引用
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" android:id="@+id/root" tools:context="com.brady.est.MainActivity" > <!-- 引入自定义组件 --> <com.brady.view.DrawView android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
时间: 2024-10-10 10:09:21