您的位置:首页 > 其它

安卓程序代写 网上程序代写[原]自定义View

2013-11-16 19:19 417 查看

一. 自定义View介绍

自定义View时, 继承View基类, 并实现其中的一些方法.

(1) ~ (2) 方法与构造相关

(3) ~ (5) 方法与组件大小位置相关

(6) ~ (9) 方法与触摸按键相关

(10) ~ (12) 方法与窗口 焦点相关

(1) 构造方法

该构造方法在创建View实例, 或者从XML布局中加载并构建界面的时候调用.

(2)加载回调方法

protected void onFinishInflate()
回调方法, 从XML布局中加载该重写的View组件的时候, 就会回调这个方法;

(3)测量方法

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
这个方法用来检测View组件以及该View组件包含的子组件的大小

(4)定位组件方法

protected void onLayout(boolean changed, int left, int top, int right,int bottom)
被重写的View组件分配在其中的子组件的位置 和 大小的时候, 回调这个方法;

(5)大小改变方法

protected void onSizeChanged(int w, int h, int oldw, int oldh)
当组件大小被改变的时候回调该方法;

(6)按键方法

public boolean onKeyDown(int keyCode, KeyEvent event)
当某个键被按下时触发该方法;

(7)松开键方法

public boolean onKeyUp(int keyCode, KeyEvent event)
当某个键松开的时候调用该方法;

(8)轨迹球事件方法

public boolean onTrackballEvent(MotionEvent event)
发生轨迹球事件时触发该方法;

(9)触摸方法

public boolean onTouchEvent(MotionEvent event)
当发生触摸时间时触发该方法;

(10)焦点改变方法

public void onWindowFocusChanged(boolean hasWindowFocus)
当组件得到, 失去焦点的时候回调的方法;

(11)组件进入窗口方法

protected void onAttachedToWindow()
当把组件放入窗口的时候, 回调这个方法

(12)组件分离窗口方法

protected void onAttachedToWindow()
当把组件从某个窗口分离触发的方法

(13)窗口可见性改变方法

protected void onWindowVisibilityChanged(int visibility)
当包含该组件的窗口发生改变的时候触发的方法

二. 实现一个跟随手指的小球View

1. 自定义View

自定义一个View组件铺满全屏, 在绘制该View组件的时候, 在onDraw()方法中根据一个xy坐标绘制一个小球;

这个xy坐标在触摸回调方法onTouchEvent()方法中动态改变, 当检测到触摸位置发生改变, 那么就重新给xy坐标赋值, 并且调用invalidate()方法重绘该组件, invalidate()方法执行后, 会回调onDraw()方法;

public class FollowBallView extends View {

public float currentX = 40;
public float currentY = 50;

Paint paint = new Paint();

public FollowBallView(Context context) {
super(context);

}

public FollowBallView(Context context, AttributeSet set) {
super(context, set);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.RED);
canvas.drawCircle(currentX, currentY, 15, paint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
currentX = event.getX();
currentY = event.getY();
//重绘
invalidate();
return true;
}
}


2. xml文件

在这个xml文件中, 引入自定义的布局, 使用完整的类名包名可以引入该自定义View组件;

引入组件后, 充满整个布局;

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<shuliang.han.followball.FollowBallView
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</RelativeLayout>


3. Activity中显示该组件

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}


4. 效果图



作者:han1202012 发表于2013-11-16 19:19:17 原文链接

阅读:53 评论:1 查看评论
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: