我尝试在按钮中手动设置高度/宽度,但它不起作用。然后实现Layoutparams。但尺寸显示很小并且没有获得所需的 dp 值。
XML
<Button
android:id="@+id/itemButton"
android:layout_width="88dp"
android:layout_height="88dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:background="#5e5789"
android:gravity="bottom"
android:padding="10dp"
android:text=""
android:textColor="#FFF"
android:textSize="10sp" />
构造函数:
public Item (int id, String name, String backgroundColor, String textColor, int width, int height){
this.id = id;
this.name = name;
this.backgroundColor = backgroundColor;
this.textColor = textColor;
this.width = width;
this.height = height;
}
Adapter:
@Override public void onBindViewHolder(final ViewHolder holder, int position) {
final Item item = items.get(position);
holder.itemView.setTag(item);
holder.itemButton.setText(item.getName());
holder.itemButton.setTextColor(Color.parseColor(item.getTextColor()));
holder.itemButton.setBackgroundColor(Color.parseColor(item.getBackgroundColor()));
ViewGroup.LayoutParams params = holder.itemButton.getLayoutParams();
params.width = item.getWidth();
params.height = item.getHeight();
holder.itemButton.setLayoutParams(params);
}
当您以编程方式指定值时LayoutParams
,这些值预计为像素。
要在像素和 dp 之间进行转换,您必须乘以当前密度因子。该值位于DisplayMetrics
,您可以从Context
:
float pixels = dp * context.getResources().getDisplayMetrics().density;
所以在你的情况下你可以这样做:
.
.
float factor = holder.itemView.getContext().getResources().getDisplayMetrics().density;
params.width = (int)(item.getWidth() * factor);
params.height = (int)(item.getHeight() * factor);
.
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)