Android的onLayout、layout方法讲解

onLayout方法是ViewGroup中子View的布局方法,用于放置子View的位置。放置子View很简单,只需在重写onLayout方法,然后获取子View的实例,,调用子View的layout方法实现布局。在实际开发中,一般要配合onMeasure测量方法一起使用。

onLayout方法:

onLayout(boolean changed,int l, int t, int r, int b);

layout方法:

public void layout(int l, int t, int r, int b); 该方法是View的放置方法,在View类实现。调用该方法需要传入放置View的矩形空间左上角left、top值和右下角right、bottom值。这四个值是相对于父控件而言的(而非绝对高度)。例如传入的是(10, 10, 100, 100),则该View在距离父控件的左上角位置(10, 10)处显示,显示的大小是宽高是90(参数r,b是相对左上角的),这有点像绝对布局。

平常开发所用到RelativeLayout、LinearLayout、FrameLayout…这些都是继承ViewGroup的布局。这些布局的实现都是通过都实现ViewGroup的onLayout方法,只是实现方法不一样而已。

下面是一个自定义ViewGroup的Demo,用onLayout和layout实现子View的水平放置,间隔是20px

{padding = 20;MyViewGroup(Context context, AttributeSet attrs) {(context, attrs);}onLayout(boolean changed, int l, int t, int r, int b) {(int i = 0, size = getChildCount(); i < size; i++) {View view = getChildAt(i);view.layout(l, t, l + 100, t + 100);l += 100 + padding;}}} Activity的XML布局:===="10dp" ><com.example.layout.MyViewGroupandroid:layout_width="match_parent"android:layout_height="100dp"<Viewandroid:layout_width="match_parent"android:layout_height="match_parent"android:background="#ff0000" /><Viewandroid:layout_width="match_parent"android:layout_height="match_parent"android:background="#00ff00" />></RelativeLayout> 效果如图所示:

上图MyViewGroup是蓝色,两个子View分别为红色和绿色。

在自定义View中,onLayout配合onMeasure方法一起使用,可以实现自定义View的复杂布局。自定义View首先调用onMeasure进行测量,然后调用onLayout方法,动态获取子View和子View的测量大小,然后进行layout布局。

何愁没有快乐的泉溪在歌唱,何愁没有快乐的鲜花绽放!

Android的onLayout、layout方法讲解

相关文章:

你感兴趣的文章:

标签云: