onLayout設置子控件的位置,對應一些普通的控件例如Button、TextView等控件,不存在子控件,所以可以不用復寫該方法。
向線性布局、相對布局等存在子控件,可以覆寫該方法去控制子控件的位置。
1、第一步首先創建一個類繼承ViewGroup
2、在該group添加一個TextView,手機運行在1080*1920的手機上,我們設置TextView的寬度是540 高的是960
3、我們首先要在OnMesure中獲得TextView的寬度和高度
4、然后在onLayout中進行設定
- protected void measureChild(View child, int parentWidthMeasureSpec,
- int parentHeightMeasureSpec)
關於View中的layout方法的四個參數,我們首先把view當成是一個矩形區域,四個參數一次代表view的左端、頂端、右端和底端距父控件坐標原點的距離
我們首先看看xml的代碼:
<?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:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="im.weiyuan.com.zidingyikongjian.MainActivity"> <im.weiyuan.com.zidingyikongjian.LayoutView android:layout_width="match_parent" android:background="@color/colorPrimaryDark" android:layout_height="match_parent"> <TextView android:text="24242425" android:background="@color/colorAccent" android:layout_width="540px" android:layout_height="960px" /> </im.weiyuan.com.zidingyikongjian.LayoutView> </LinearLayout>
我們再來看看程序的代碼
package im.weiyuan.com.zidingyikongjian; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; /** * Created by wei.yuan on 2017/6/2. */ public class LayoutView extends ViewGroup { public LayoutView(Context context) { super(context); } public LayoutView(Context context, AttributeSet attrs) { super(context, attrs); } public LayoutView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } //首先要獲得當前控件中的寬度和高度,才能在onLayout中去知道控件的寬度和高度 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int childCount = getChildCount();//判斷是否存在子控件 if(childCount >0){ Log.d("123456","onMeasure is called"); View childView = getChildAt(0);//獲得第一個子控件 //測量出當前子控件的大小 measureChild(childView,widthMeasureSpec,heightMeasureSpec); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childCount = getChildCount();//判斷是否存在子控件 if(childCount >0){ View childView = getChildAt(0);//獲得第一個子控件 //讓子控件在屏幕的中點開始填充屏幕 int childWidth = childView.getMeasuredWidth();//主要getMeasuredWidth函數的值必須調用了measureChild才存在值 int childHeigth = childView.getMeasuredHeight(); Log.d("123456 childWidth",""+childWidth); Log.d("123456 childHeigth",""+childHeigth); childView.layout(540,0,childWidth+540,childHeigth);//設置子控件的位置,需要首先獲得子控件的大小 } } }
我們來看看程序運行的效果:
上面如果設置成
childView.layout(0,0,childWidth,childHeigth);//設置子控件的位置,需要首先獲得子控件的大小
運行的效果是: