如何将自定义视图置于Android内置的视图中?

时间:2010-03-11 15:54:51

标签: android

我正在为Android开发一款小应用。我正在创建自己的观点。

我打算将布局设计为:

<LinearLayout>
   <MyView>
   <Button><Button>
</LinearLayout>

但是当我运行程序时,我的自定义视图将覆盖整个屏幕。反正有没有避免这个?

我已尝试将android:layout_widthlayout_height添加为wrap_contentfill_partent,但没有运气。

3 个答案:

答案 0 :(得分:1)

我通常会将FrameLayout放在我想要自定义视图的位置,然后是代码我创建我的视图并将其添加到FrameLayout

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#0BF">

    <FrameLayout
        android:id="@+id/GLFrame"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <FrameLayout
        android:id="@+id/ActivityFrame"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent" />

</FrameLayout>

来自这样的代码的访问。

FrameLayout glFrame = (FrameLayout)findViewById(R.id.GLFrame);
glFrame.addView(new NativeBackgroundSurface(this));

答案 1 :(得分:0)

假设您希望布局占用除按钮占用的空间之外的所有内容,您需要布置按钮,然后使视图与其父项顶部对齐并在按钮上方布局:

 <RelativeLayout 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"
>

<Button android:layout_width= whatever 
android:layout_height= whatever
    android:id="@+id/button"
    android:layout_alignParentBottom="true" />

<MyView android:layout_width="fill_parent" 
android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_above ="@id/button"/>

</RelativeLayout>

答案 2 :(得分:0)

除了已经提出的方法之外,这是另一种方式。如果您知道该视图的大小,或者您可以通过编程方式确定其大小,则可以覆盖onMeasure方法,该方法告诉操作系统视图的大小。例如,如果您正在编写游戏或使用Canvas的内容,那么您可以使用getHeight()getWidth()方法,或者您可以直接从您使用的任何参数中获取大小你创建了你的画布。 onMeasure易于使用:

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
    setMeasuredDimension(width, height);
}

如果您需要有关参数的更多信息,请参阅documentation。 (如果它没有多大意义,请不要担心,它也不适合我:P但你可以使用它而不需要担心widthMeasureSpec和heightMeasureSpec,只要你可以计算视图应该是的大小正确。)