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);//设置子控件的位置,需要首先获得子控件的大小
运行的效果是: