首页 > 代码库 > UI复习-自定义View(触摸画圆)
UI复习-自定义View(触摸画圆)
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>
UI复习-自定义View(触摸画圆)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。