0

I have created a custom subclass of AppCompatButton called SquareButton, which forces a button to be square. The code for that subclass was found here: https://stackoverflow.com/a/36991823/7648952.

This button works fine and displays when the layout it's contained in is inflated outside of a RecyclerView, however when used with a RecyclerView the button does not display. When I change my layout and code to use a normal Button, the Button displays, so there doesn't seem to be anything wrong with the way I'm using RecyclerView. I have no idea why this might be.

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

Screenshot of the SquareButton working when inflated outside of a RecyclerView: enter image description here

Screenshot of the SquareButton not displaying inside of RecyclerView: enter image description here

Screenshot of a regular Button working inside of RecyclerView: enter image description here

It seems to me that this behavior is odd. Any help would be much appreciated.

sbearben
  • 323
  • 6
  • 16

1 Answers1

1

Try this code block:

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

In this usage, you will set widthMeasureSpec or heightMeasureSpec instead of direct width or height value.

Oğuzhan Döngül
  • 7,856
  • 4
  • 38
  • 52
  • That did the trick! The only thing I changed in your code was exhange getMeasuredHeight() and getMeasured\width() in the if/else statement at the bottom. Appreciate your help. – sbearben May 01 '18 at 18:57