自定义view-跟随手指动的小球

View组件类似于javaSwing中的JPanel。它只是一个巨型的空白区域,view组件内没有任何的内容,对于android的其他组件来说,他们都继承了view组件,并在view所提供的空白区域进行外观编辑,

 

下面是view开发是所用到的回调方法:

 

onFinishInflate() 当View中所有的子控件均被映射成xml后触发
onMeasure(int, int) 确定所有子元素的大小
onLayout(boolean, int, int, int, int) 当View分配所有的子元素的大小和位置时触发
onSizeChanged(int, int, int, int) 当view的大小发生变化时触发
onDraw(Canvas) view渲染内容的细节
onKeyDown(int, KeyEvent) 有按键按下后触发
onKeyUp(int, KeyEvent) 有按键按下后弹起时触发
onTrackballEvent(MotionEvent) 轨迹球事件
onTouchEvent(MotionEvent) 触屏事件
onFocusChanged(boolean, int, Rect) 当View获取或失去焦点时触发
onWindowFocusChanged(boolean) 当窗口包含的view获取或失去焦点时触发
onAttachedToWindow() 当view被附着到一个窗口时触发
onDetachedFromWindow() 当view离开附着的窗口时触发
onWindowVisibilityChanged(int) 当窗口中包含的可见的view发生变化时触发

 

 

实例:随手指动的小球

 

自定义组件:

 

package cn.haozi;

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);

}

public void onDraw(Canvas canvas){

super.onDraw(canvas);
//创建一个画笔
Paint p = new Paint();
//设置画笔的颜色
p.setColor(Color.BLUE);
//绘制一个小球
canvas.drawCircle(currentX, currentY, 15, p);


}


}

activity类:

package cn.haozi;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;

public class DrawroolActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

LinearLayout root = (LinearLayout) findViewById(R.id.root);

final Drawview draw = new Drawview(this);

draw.setMinimumHeight(300);
draw.setMinimumWidth(500);

//为draw添加绑定touch事件

draw.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View agr0, MotionEvent event) {
//修改draw组件的两个属性
draw.currentX = event.getX();
draw.currentY = event.getY();

//重绘
draw.invalidate();



return false;
}
});
root.addView(draw);

}
}

 

 

 

 

你可能感兴趣的:(原创,Android,自学日记)