Android : 按钮超出屏幕边缘

Android : buttons go off the edge of the screen

我在线性布局中有一个 table 布局 在 table 行中的 3 个按钮充气后,最后一个按钮离开屏幕 我的意思是 3 个按钮不适合屏幕宽度 我该怎么办?

这是代码

<TableLayout
    android:id="@+id/buttonTableLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:stretchColumns="0,1,2"
    android:layout_weight="1">

    <TableRow
        android:id="@+id/tableRow0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </TableRow>

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </TableRow>

</TableLayout>

TableRow 不检查其内容是否适合屏幕尺寸。我猜你的按钮占用了所有 Space,因此最后一个按钮在屏幕之外。

我可以想到 2 个解决这个问题的方法:

  • 为每个按钮使用带权重的 LinearLayout:

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    
            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:layout_weight="1.0" />
    
            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:layout_weight="1.0" />
    
    </LinearLayout>
    

    当然,您也可以通过编程方式执行此操作。 可以在此处找到有关权重的更多信息:https://developer.android.com/guide/topics/ui/layout/linear.html

  • 使用流式布局。它会自动检查您的视图是否适合当前行,如果不够,则将它们放在下一行 space。我自己使用的一个很好的开源库是这个:https://github.com/ApmeM/android-flowlayout