怎样才能使按钮沿XML布局均匀分布并使文本适合呢?



我在每个按钮上使用android:layout_weight="1"时都使用了android:layout_height="0dp"。但是如果字符串太长,大小仍然会改变。我怎样才能使按钮的大小不变,而使文本适合?

(这是一个测验应用程序,我在四个按钮上生成随机字符串,所以我使用了两个水平方向的线性布局)

<LinearLayout 
    android:id="@+id/ll1"
    android:layout_marginTop="30dp"
    android:layout_below="@+id/textView2"
    android:weightSum="2"
    android:orientation="horizontal"
    android:layout_width="0dp"
    android:layout_height="wrap_content">
    <Button
        android:layout_weight="1"
        android:layout_marginRight="2dp"
        android:textColor="#000"
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/mybutton"
        android:text="Button" />
    <Button
        android:layout_marginLeft="2dp"
        android:layout_weight="1"
        android:textColor="#000"
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:background="@drawable/mybutton"
        android:text="Button" />

    </LinearLayout>
        <LinearLayout 
        android:id="@+id/ll2"
        android:layout_marginTop="20dp"
        android:layout_below="@+id/ll1"
        android:weightSum="2"
        android:orientation="horizontal"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        >
     <Button
        android:layout_marginRight="2dp"
        android:layout_weight="1"
        android:textColor="#000"
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/mybutton"
        android:text="Button" />
    <Button
        android:layout_marginLeft="2dp"
        android:textColor="#000"
        android:layout_weight="1"
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/mybutton"
        android:text="Button" />

</LinearLayout>

我认为从你的描述你是使用线性布局错误。对于水平方向,您希望将宽度设置为0dp。请看下面的代码:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="two"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="two"/>
</LinearLayout>

android:singleLine="true" 

将上述内容添加到按钮字段。它会省略你的文本,但它会强制使用一行…

你真的有几个选择:省略号,较小的字体大小,更好的控制布局别名(http://developer.android.com/guide/topics/resources/providing-resources.html)

使用布局别名,您可以为不同大小/dpi/方向/宽度/高度的屏幕指定不同的布局,从而指定一个工作和适合的字体大小

最新更新