dispatchDraw()和onDraw()的区别
2022-12-06 12:50:15
michael007js
122
onDraw()先于dispatchDraw()执行,用于本身控件的绘制,dispatchDraw()用于子控件的绘制
onDraw()绘制的内容可能会被子控件覆盖而dispatchDraw()是子控件的绘制,所以是覆盖在onDraw()上的
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<com.example.myviewpage.ViewPagerIndicator
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#999999"
android:id="@+id/main_vpi">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="标题1"
android:background="#f00"
android:gravity="center"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="标题2"
android:gravity="center"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="标题3"
android:gravity="center"/>
</com.example.myviewpage.ViewPagerIndicator>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mian_vp"/>
</LinearLayout>
ViwPagerIndicator是继承自LinearLayout的自定义控件目的是绘制一个三角形的指示器
ViwPagerIndicator使用dispatchDraw():
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
canvas.save();
canvas.translate(minitTrianslationX+mTrianslationX,getHeight());
canvas.drawPath(path,paint);
canvas.restore();
Log.i(TAG, "dispatchDraw: ");
}
效果:
ViwPagerIndicator使用dispatchDraw():
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.translate(minitTrianslationX+mTrianslationX,getHeight());
canvas.drawPath(path,paint);
canvas.restore();
Log.i(TAG, "onDraw: ");
}
效果: