實現效果圖:
實現方式:
繼承View類自己重繪一個圓,然後將這個自定義的繼承於View類的加入到當前的Activity並且為這個自定義的View控件添加一個onTouchLitener事件
Android應用小實例--跟隨手指的小球源代碼下載:
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /pub/Android源碼集錦/2011年/11月/Android應用小實例--跟隨手指的小球/
自定義組件繼承於View類:
- package com.jiahui.draw;
-
- import android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.view.View;
-
- public class DrawView extends View {
-
- public float currentX=40;
- public float currentY=50;
-
- //必須重寫一個構造方法
- public DrawView(Context context) {
- super(context);
- // TODO Auto-generated constructor stub
- }
- //重寫onDraw方法通過Canvas繪畫
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- //創建畫筆
- Paint paint=new Paint();
- paint.setColor(Color.RED);
- //繪制一個小圓
- canvas.drawCircle(currentX, currentY, 25, paint);
-
- }
-
- }
將自定義的組件添加到當前的Activity
- package com.jiahui.draw;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.MotionEvent;
- import android.view.View;
- import android.widget.LinearLayout;
-
- public class CustomeViewActivity extends Activity {
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- LinearLayout root=(LinearLayout) findViewById(R.id.root);
-
- //創建一個自己繼承於View的對象
- final DrawView drawView=new DrawView(this);
- //設置自定義組件的最大寬度和高度
- drawView.setMinimumWidth(300);
- drawView.setMinimumHeight(500);
-
- drawView.setOnTouchListener(new View.OnTouchListener() {
- public boolean onTouch(View v, MotionEvent event) {
- drawView.currentX=event.getX();
- drawView.currentY=event.getY();
- //重繪
- drawView.invalidate();
- //返回true表明算是方法已經處理該事件
- return true;
- }
- });
- root.addView(drawView);
- }
- }
main.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical"
- android:background="#99FFCC"
- android:id="@+id/root">
- </LinearLayout>