首页 > 解决方案 > RecyclerView 不显示自定义按钮

问题描述

我创建了一个名为 SquareButton 的自定义 AppCompatButton 子类,它强制按钮为方形。该子类的代码可在此处找到:https ://stackoverflow.com/a/36991823/7648952 。

此按钮工作正常,并在其包含的布局在 RecyclerView 外部膨胀时显示,但是当与 RecyclerView 一起使用时,该按钮不显示。当我更改布局和代码以使用普通 Button 时,会显示 Button,因此我使用 RecyclerView 的方式似乎没有任何问题。我不知道为什么会这样。

SquareButton.java:

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;

public class SquareButton extends AppCompatButton {

    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);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int size = width > height ? height : width;
        setMeasuredDimension(size, size);
    }
}

SquareButton 在 RecyclerView 外部充气时工作的屏幕截图: 在此处输入图像描述

SquareButton 的屏幕截图未显示在 RecyclerView 内: 在此处输入图像描述

在 RecyclerView 中工作的常规 Button 的屏幕截图: 在此处输入图像描述

在我看来,这种行为很奇怪。任何帮助将非常感激。

标签: androidandroid-recyclerviewandroid-button

解决方案


试试这个代码块:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    if(width > height){
        setMeasuredDimension(getMeasuredHeight(), getMeasuredHeight());
    }else {
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
    }
}

在这种用法中,您将设置widthMeasureSpecheightMeasureSpec而不是直接的宽度高度值。


推荐阅读