MainActivity.java
package com.kale.drawview; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.RelativeLayout; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* RelativeLayout root = (RelativeLayout)findViewById(R.id.root_relativeLayout_id); final DrawView drawView = new DrawView(this); //設置組件的最大寬度 drawView.setMinimumHeight(300); drawView.setMinimumWidth(500); root.addView(drawView);*/ } }
DrawView.java 自定义的view
package com.kale.drawview; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class DrawView extends View{ public float currentX = 60; public float currentY = 60; //定义,创建画笔 Paint paint = new Paint(); public DrawView (Context context) { super(context); } public DrawView(Context context,AttributeSet set) { super(context,set); } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); //设置画笔颜色 paint.setColor(Color.RED); //绘制一个小圆 canvas.drawCircle(currentX, currentY, 50, paint); } // 为该组件的触碰时间2重写处理的方法 @Override public boolean onTouchEvent(MotionEvent event) { // 修改坐标 currentX = event.getX(); currentY = event.getY(); // 通知组件,重新绘制自己 invalidate(); // 返回true表明该方法已经处理该事件 return true; } }
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root_relativeLayout_id" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <com.kale.drawview.DrawView android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout>