自定义view组件

时间:2023-03-09 09:19:18
自定义view组件

参考《疯狂android讲义》第2版 2.1节P48,对应CustomViewDemo.zip。

若在开发过程中,发现现有的view均不能满足需要,可以自定义一个view。

自定义一个view 的关键在于重写view类的几个核心方法,如onDraw, onTouchEvent等。

自定义view类:

DrawBall.java

package com.ljh.customviewdemo.ui;

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 DrawBall extends View { private Paint p = new Paint();
private float currentX = 40;
private float currentY = 50; public DrawBall(Context context) {
super(context);
} public DrawBall(Context context, AttributeSet set) {
super(context, set);
} @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 = event.getX();
currentY = event.getY(); /*
* Invalidate the whole view. If the view is visible,
* onDraw(android.graphics.Canvas) will be called at some point in the
* future. This must be called from a UI thread. To call from a non-UI
* thread, call postInvalidate().
*/
invalidate();
return true;
} }

Activity类:MainAtivity.java

package com.ljh.customviewdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }

布局文件:activity_main.xml

<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <!-- 注意:此处使用类的全路径,标明ui类型。 -->
<com.ljh.customviewdemo.ui.DrawBall
android:layout_width="wrap_content"
android:layout_height="wrap_content"/> </RelativeLayout>

注意,activity中包括多个view。一个activity对应一个布局文件,布局文件中包括多个view,这些view可以是android定义好的,或者自定义的。