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);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//設定畫筆的顏色p.setColor(Color.RED);//繪製一個小球canvas.drawCircle(currentX, currentY, 15, p);}/** * 為該組件的觸碰事件重寫事件處理方法 */@Overridepublic 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 {@Overrideprotected 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);}}
效果:
<喎?http://www.bkjia.com/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 {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.custom_layout);}}