在Android中扩展View类和布局

时间:2012-12-09 12:07:06

标签: android layout android-custom-view

我在Android中使用布局和视图。我的布局如下:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        <com.mycode.MyView
            android:id="@+id/MyView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
        />

        <LinearLayout
            android:id="@+id/leftpane"
            android:layout_width="55dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.95"
            android:background="@color/leftpane_background"
            android:gravity="center"
            android:orientation="vertical"
            android:scrollbarStyle="insideOverlay" >

        </LinearLayout>
</LinearLayout>

如果我对行<com.mycode.MyView .... />进行注释,则会显示左侧线性布局(带有id左侧窗格),否则不会显示。如果我在左窗格布局后添加另一个布局(例如滚动视图布局),它也不会显示。 为什么使用我的自定义视图(MyView)会消除所有其他布局? 我想做的是将我的自定义视图作为应用程序的背景,我将在其中显示图像,以及其他一些背景视图,如滚动视图,按钮等。 这是MyView类的代码。请记住,我需要在活动的背景上绘制图像(在整个背景上,显然不包括操作栏):

/**
*/
class   MyView extends View
{
    TextPaint   text_paint;
    Paint       paint;

    private void    InitView()
    {
        text_paint = new TextPaint( Paint.ANTI_ALIAS_FLAG );
        text_paint.setColor( Color.BLACK );
        paint = new Paint();
    }

    public MyView(Context context)
    {
        super(context);
        InitView();
    }

    public MyView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        InitView();
    }


    public MyView(Context context, AttributeSet attrs, int defaultStyle)
    {   
        super(context, attrs, defaultStyle);
        InitView();
    }


    @Override
    protected void  onDraw( Canvas canvas )
    {
        super.onDraw(canvas);
        //int   w, h;
        //w = canvas.getWidth();
        //h = canvas.getHeight();
        //paint.setColor( Color.WHITE );
        //canvas.drawRect(0, 0, w-1, h-1, paint );
        //canvas.drawText( "ciao", 100, 100, text_paint);
    }

};

2 个答案:

答案 0 :(得分:0)

尝试将视图的高度更改为:

android:layout_height="wrap_content" 

答案 1 :(得分:0)

当你在自定义MyView中覆盖onMeasure方法时,也许你做了一些错误工作, 所以MyView匹配所有父视图。 您能否在MyView的onLayout和onMeasure方法中显示您的代码。

相关问题