Android繪制跟隨手指移動的小球
為了實現(xiàn)一個跟隨手指移動的小球,考慮到開發(fā)自定義的UI組件,這個UI組件將會在一個指定的位置繪制一個小球,這個位置可以動態(tài)改變。當(dāng)用戶手指在屏幕上拖動時,程序監(jiān)聽到這個手指的動作,并且傳入UI組件,通知組件重繪即可。話不多說,上代碼:
在java的DrawView中:
package com.example.test01; 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; import androidx.annotation.Nullable; public class DrawView extends View { private float currentX=40f; private float currentY=50f; // 定義并創(chuàng)建畫筆 private Paint p=new Paint(); public DrawView(Context context) { super(context); } public DrawView(Context context, @Nullable AttributeSet set) { super(context, set); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 設(shè)置畫筆的顏色 p.setColor(Color.RED); // 設(shè)置一個小球 canvas.drawCircle(currentX,currentY,15F,p); } // 為該事件的觸碰事件重寫處理方法 @Override public boolean onTouchEvent(MotionEvent event) { // 修改成員變量 currentX=event.getX(); currentY=event.getY(); // 通知當(dāng)前組件重繪自己 invalidate(); // 返回true說明該處理方法已經(jīng)處理自己 return true; } }
在java的MainActivity中:
package com.example.test01; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); } }
在layout中:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <com.example.test01.DrawView android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
運行效果如下:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
android開發(fā)基礎(chǔ)教程—三種方式實現(xiàn)xml文件解析
本文將介紹三種方式:sax方式/dom方式/pull方式實現(xiàn)xml文件解析,感興趣的朋友可以了解下2013-01-01android TextView 設(shè)置和取消刪除線的兩種方法
這篇文章主要介紹了android TextView 設(shè)置和取消刪除線的兩種方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03基于Android studio3.6的JNI教程之ncnn之語義分割ENet
這篇文章主要介紹了基于Android studio3.6的JNI教程之ncnn之語義分割ENet的相關(guān)知識,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值 ,需要的朋友可以參考下2020-03-03Android中導(dǎo)航組件Navigation的實現(xiàn)原理
大家好,本篇文章主要講的是Android中導(dǎo)航組件Navigation的實現(xiàn)原理,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-02-02