Android 如何在dp值中设置Layoutparams高度/宽度?
我试着在按钮中手动设置高度/宽度,但不起作用。然后实现了Layoutparams。但尺寸较小,无法获得所需的dp值 XMLAndroid 如何在dp值中设置Layoutparams高度/宽度?,android,xml,android-layout,android-adapter,Android,Xml,Android Layout,Android Adapter,我试着在按钮中手动设置高度/宽度,但不起作用。然后实现了Layoutparams。但尺寸较小,无法获得所需的dp值 XML <Button android:id="@+id/itemButton" android:layout_width="88dp" android:layout_height="88dp" android:layout_marginRight="5dp" android:layout_marginBottom="5dp"
<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;
}
@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
中,您可以从上下文访问该值:
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);
.
.
我认为您应该使用在dimens中定义的dp值以及。在自定义视图中,Kotlin实现如下所示:
val layoutParams = layoutParams
val width = context.resources.getDimensionPixelSize(R.dimen.width_in_dp)
layoutParams.width = width
你的解释非常清楚和准确!谢谢你,伙计!成功了!
val layoutParams = layoutParams
val width = context.resources.getDimensionPixelSize(R.dimen.width_in_dp)
layoutParams.width = width