View组件在布局中是一个矩形是空白区域,没有任何内容。而UI组件之所以有内容,是因为继承了View组件之后在其提供的空白区域上重新绘制外观。这就是Android的UI组件的实现原理。
自定义UI组件需要重写的方法:
重写方法 | 说明 |
---|---|
构造方法 | 当Java代码中重建了一个View实例或者XML布局文件加载并构建界面时将需要调用该构造器 |
onFinishInflate() | 从XML布局文件中加载指定组件并利用它来构建界面时,该回调方法被调用 |
onLayout(boolean,int,int,int) | 当该组件需要分配其子组件的位置、大小时,该方法会被调用 |
onDraw(Canvas) | 当该组件将要绘制它的内容时回调该方法进行绘制 |
onSizeChanged(int,int,int,int) | 当该组件的大小被改变时回调该方法 |
onTouchEvent(MotionEvent) | 当触摸屏幕时触发该方法 |
onKeyDown(int,KeyEvent) | 某个键被按下时触发该方法(同理还有onKeyUp()) |
onTrackballEvent(MotionEvent) | 当发生轨迹球事件时触发该事件 |
onFocusChanged(boolean gainFocus,int direction,Rect previouslyFousedRect) | 当该组件焦点发生改变时触发该方法 |
onWindowFocusChanged(boolean) | 当包含该组件的窗口失去或得到焦点时触发该方法 |
onAttachedToWindow() | 当把该组件放入某窗口时触发该方法 |
onDetachedFromWindow() | 当把该组件从某个窗口上分离时触发 |
onWindowVisibilityChanged(int) | 包含该组件的窗口的可见性发生改变时触发该方法 |
例:自定义UI的例子,让小球跟随手指在屏幕上的滑动而滑动
BallView.java
public class BallView extends View {
public float currentX=60;
public float currentY=60;
//定义并创建画笔
Paint paint=new Paint();
public BallView(Context context) {
super(context);
}
public BallView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//设置画笔的颜色
paint.setColor(Color.RED);
//画一个圆
canvas.drawCircle(currentX,currentY,20,paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//修改 currentX,currentY的值
currentX=event.getX();
currentY=event.getY();
//通知当前组件重新绘制自己
invalidate();
//表明该处理方法已经处理了该事件
return true;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
}
}
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/root_view">
<com.example.test_application.BallView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
运行结果如下:
鼠标放在屏幕的任意位置,小球会跟随鼠标的移动而移动,非常好玩