Issue
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:
Screenshot of the SquareButton not displaying inside of RecyclerView:
Screenshot of a regular Button working inside of RecyclerView:
It seems to me that this behavior is odd. Any help would be much appreciated.
Solution
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.
Answered By - Oğuzhan Döngül
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.