首页 > 解决方案 > 圆形按钮在网格布局中显示为矩形

问题描述

我正在尝试使用带有网格布局的回收器视图显示许多圆形按钮。但是,当我在模拟器上运行应用程序时,按钮显示为正方形。我注意到,当我查看按钮布局文件的设计视图时,存储按钮的约束布局在按钮周围有一个透明矩形。我不确定我的程序是否会自动填充约束视图背景以及按钮,但我只是想让你知道。这是我的 recyclerview 中的 onbindviewholder 方法,它填充了我的按钮的颜色(colorResources 是我的回收器视图中的一个数组,它包含我想要填充按钮的颜色):

 @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.button.setBackgroundColor(getResources().getColor(colorResources[position]));
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickedColor=colorResources[position];
            }
        });
    }

这是我的 recyclerview/gridlayout 中显示的按钮 xml 文件:

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp">
<Button
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/button_color_background"
    android:id="@+id/colorButton" />
</androidx.constraintlayout.widget.ConstraintLayout>

这是上面代码中提到的我的按钮的背景 xml 文件:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <corners android:radius="999dp"/>
    <solid android:color="@color/purple_700"/>
    <stroke android:width="50px" android:color="#636161"/>
</shape>

如果您需要有关我的代码的任何其他信息,请告诉我。

提前致谢

标签: javaandroid

解决方案


只需设置按钮的宽度和高度:如:

android:layout_width="50dp"
android:layout_height="50dp"

推荐阅读