android - 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 的屏幕截图:
在我看来,这种行为很奇怪。任何帮助将非常感激。
解决方案
试试这个代码块:
@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());
}
}
在这种用法中,您将设置widthMeasureSpec或heightMeasureSpec而不是直接的宽度或高度值。
推荐阅读
- javascript - 使用 .has() 时 jQuery 不是函数
- python - 相同的代码具有不同的结果
- python - 使用 pandas 计算平均值时排除列中的零
- android - 如何在 kotlin 中删除错误“未解析的参考文本”
- c++ - 链接对静态方法的调用
- json - 如何使用 groovy 脚本比较 JSON 响应中的多个对象
- css - 如何使用自定义图标字体?
- docker - 试图在 VM 内的 docker 中启动 Xdebug 会话以访问我的远程计算机
- r - 如何在R中的条形图中的列之间放置标签?
- asp.net - 如何在 Azure 上托管 OData V4 Web API