Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 自定義組件隨著手指自動畫圓

android 自定義組件隨著手指自動畫圓

編輯:關於Android編程

首先自定義一個View子類:

package com.example.androidtest0.myView;

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 = 40;
	public float currentY = 50;
	//定義、並創建畫筆
	Paint p = new Paint();
	public DrawView(Context context) {
		super(context);
	}

	public DrawView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		//設置畫筆的顏色
		p.setColor(Color.RED);
		//繪制一個小球
		canvas.drawCircle(currentX, currentY, 15, p);
	}
	
	/**
	 * 為該組件的觸碰事件重寫事件處理方法
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		//修改currentX、currentY兩個屬性
		currentX = event.getX();
		currentY = event.getY();
		//通知當前組件重繪自己
		invalidate();
		return true;
	}
	
    
	

}

主界面XML:

custom_layout.xml









主activity:

package com.example.androidtest0;

import com.example.androidtest0.myView.DrawView;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;

public class CustomView extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.custom_layout);
		//獲取布局文件中LinearLayout容器
		LinearLayout root = (LinearLayout)findViewById(R.id.root);
		//創建DrawView組件
		final DrawView drawView = new DrawView(this);
		//設置自定義組件的最小寬度、高度
		drawView.setMinimumWidth(10);
		drawView.setMinimumHeight(10);
		root.addView(drawView);
	}
}
效果:

\

<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+s/20y9auzeKjujwvcD4KPHA+u7m/ydLU08NYTUy1xLe9yr2jutKyysfK18/IvajSu7j2Vmlld7XE19PA4KOsus3Jz8Pm0rvR+aGjyLu689b3vefD5lhNTMjnz8KjujwvcD4KPHA+PHByZSBjbGFzcz0="brush:java;">


主activity文件如下:

package com.example.androidtest0;

import com.example.androidtest0.myView.DrawView;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;

public class CustomView extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.custom_layout);
	}
}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved