自定义View,随着手指运动的小球

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>




 

posted @   developer_Kale  阅读(358)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
网站流量统计工具
点击右上角即可分享
微信分享提示