自定义组件布局顺序

时间:2013-01-11 11:52:20

标签: java android android-layout android-custom-view

我有一个自定义组件覆盖了onLayout方法,如下所示:

@Override
    public void onLayout(boolean changed, int left, int top, int right, int bottom) {
        int[] location = new int[2];
        this.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];
        int w = this.getWidth();
        int h = y+(8*CELL_HEIGHT);

        updateMonthName();
        initCells();

        CELL_MARGIN_LEFT = 0;
        CELL_MARGIN_TOP = monthNameBounds.height();
        CELL_WIDTH = w / 7;

        setFrame(x, y, x+w, h);
        super.onLayout(true, x, y, w, h);
    }

但是,在线性布局中使用此组件时,如下所示:

<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"
    tools:context=".MainActivity"
    android:padding="10dp"
    android:orientation="vertical">

    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TextView above"
        android:textSize="15sp"
        />

    <com.project.calenderview.CalendarView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TextView below"
        android:textSize="15sp"
        />

</LinearLayout>

渲染布局使得textview“上面的TextView”是第一个,“TextView below”是第二个,然后是我的组件,它应该位于两者之间。

编辑: 这里也是onDraw:

@Override
    protected void onDraw(Canvas canvas) {
        // draw background
        super.onDraw(canvas);

        //Draw month name
        canvas.drawText(monthName, (this.getWidth() / 2) - (monthNameBounds.width() / 2), monthNameBounds.height() + 10, monthNamePaint);

        //Draw arrows
        monthLeft.draw(canvas);
        monthRight.draw(canvas);

        // draw cells
        for(Cell[] week : mCells) {
            for(Cell day : week) {
                if(day == null) continue;
                day.draw(canvas);   
            }
        }

    }

这里做错了什么?

由于

1 个答案:

答案 0 :(得分:0)

onLayout方法正在传递int left, int top, int right, int bottom,指示您的视图应该绘制的位置,但显然您完全忽略它。您可以使用这些值来正确布局。

修改

如果您没有扩展ViewGroup,则不应该覆盖onLayout(bool, int, int, int, int)

来自文档View.onLayout

  

当此视图应指定大小和位置时,从布局调用   每个孩子。带子项的派生类应该覆盖   这个方法和他们每个孩子的呼叫布局。

带子项的派生类应覆盖此方法并在每个子项上调用布局

您对最终结果的问题在于代码的其他部分。