0

我在我的 Android 应用中有一个相当简单的 Activity,它显示三个按钮,每个按钮启动一个不同的 Activity。目前,我使用RelativeLayout 将中间按钮水平和垂直居中,然后将顶部和底部按钮与中间按钮相距30dp(并且水平居中)。

然而,我想做的是让按钮拉伸到屏幕宽度的一定百分比。我不知道如何做到这一点并保持按钮居中。是否有一个好的对象可以用作按钮两侧的 LinearLayout 中的“填充物”(所以我可以设置权重)?或者有没有一种不涉及LinearLayout的方法?

布局的 XML 是:

<RelativeLayout 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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button2"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="30dp"
        android:onClick="button1Callback"
        android:text="@string/button1Label" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:onClick="button2Callback"
        android:text="@string/button2Label" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="@string/button3Label" />

</RelativeLayout>
4

1 回答 1

1

当然。查看或框架都可以工作。

<LinearLayout android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <View android:layout_height="0dp"  
    android:layout_width="0dp"
    android:layout_weight="60" />
   <Button android:layout_height="wrap_content"  
    android:layout_width="0dp"
    android:layout_weight="20" />
   <View android:layout_height="0dp"  
    android:layout_width="0dp"
    android:layout_weight="20" />
 </LinearLayout>

作为垫片工作得很好,据我所知似乎完全无害。我在我的应用程序中经常使用它(尽管老实说,我的大多数按钮都是固定宽度的)。

有一次,我实际上编写了一个具有比例布局的自定义视图。但最后我根本没有使用它。在几乎所有情况下,您都可以在线性布局中明智地应用权重来获得等效的比例布局。

于 2013-01-02T20:57:00.717 回答