android - 如何在 dp 值中设置 Layoutparams 高度/宽度?

标签 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"
    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 中,您可以从 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);
.
.

关于android - 如何在 dp 值中设置 Layoutparams 高度/宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41659338/

相关文章:

java - 默认处理程序上的存储错误

android - CardViews 未显示在 RecyclerView 中

android - 初学者 Android 开发 : findViewById issue

android - 从另一个资源中绘制位图

android - 在 Android 中实现 Picasa

java - Android:SimpleAdapter notifyOnDataSetChanged 不会触发 getView

java - 由于 XML 文件中有空格,无法读取 XML

c# - 序列化从 WebService 到对象的 XML 响应 (C#)

android - 如何在android中创建弹出模式窗口

android - 无法访问 Android 11 上的 obb 目录