如何创建填充屏幕宽度的精确方形按钮

Bep*_*ppe 5 android android-layout android-tablelayout

我有一个活动,根据TableLayout和TableRow动态填充一些按钮,如下所示:

    private TableLayout buttonTableLayout;
    //-----
    for (int row = 0; row < buttonTableLayout.getChildCount(); ++row)
        ((TableRow) buttonTableLayout.getChildAt(row)).removeAllViews();

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    for (int row = 0; row < 5; row++) {
        TableRow currentTableRow = getTableRow(row);

        for (int column = 0; column < 5; column++) {
                Button newGuessButton = (Button) inflater.inflate(R.layout.my_button, currentTableRow, false);
                newGuessButton.setText(String.valueOf((row * 5) + column + 1));
                currentTableRow.addView(newGuessButton);
            }

        }
    }
    //----
    private TableRow getTableRow(int row) {
        return (TableRow) buttonTableLayout.getChildAt(row);
    }
Run Code Online (Sandbox Code Playgroud)

我想制作一个5*5的按钮列表1:它们都具有相同的宽度和高度,2:使它们填满屏幕.在我的代码中,我有一个名为my_button的布局,如:

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/newButton"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="@drawable/button_style"></Button>
Run Code Online (Sandbox Code Playgroud)

要么

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/newButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/button_style"></Button>
Run Code Online (Sandbox Code Playgroud)

结果是: 在此输入图像描述 在此输入图像描述

我已经改变了重力,但它不起作用.有没有办法让它们完全正方形并填充屏幕的宽度.

Kin*_*uoc 11

你应该在子类Button视图和覆盖下面的函数:

public class SquareButton extends Button {
public SquareButton(Context context) {
    super(context);
}

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

public SquareButton(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public SquareButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    int size = width > height ? height : width;
    setMeasuredDimension(size, size); // make it square

}
}
Run Code Online (Sandbox Code Playgroud)

编辑:好的,你需要自定义你的按钮,如上所述.然后,您可以使用上面的SquareButton,而不是使用默认按钮.

 <com.kingfisher.utils.SquareButton
            android:id="@+id/btnSearch"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="100"
            android:text="Downloaded"/>
Run Code Online (Sandbox Code Playgroud)