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

4 xml android 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" />
Run Code Online (Sandbox Code Playgroud)

构造函数:

  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;

}
Run Code Online (Sandbox Code Playgroud)

适配器:

@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);

}
Run Code Online (Sandbox Code Playgroud)

rup*_*pps 21

当您以编程方式指定值时LayoutParams,这些值应为像素.

要在像素和dp之间进行转换,您必须乘以当前的密度因子.该值位于DisplayMetrics,您可以从以下位置访问Context:

float pixels =  dp * context.getResources().getDisplayMetrics().density;
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下你可以这样做:

.
.
float factor = holder.itemView.getContext().getResources().getDisplayMetrics().density;
params.width = (int)(item.getWidth() * factor);
params.height = (int)(item.getHeight() * factor);
.
.
Run Code Online (Sandbox Code Playgroud)

  • 你的解释非常清楚准确!谢啦!有效! (2认同)

Tat*_*aki 6

选项 1:使用dimens.xml

view.updateLayoutParams {
    width = resources.getDimensionPixelSize(R.dimen.my_width)
    height = resources.getDimensionPixelSize(R.dimen.my_height)
}
Run Code Online (Sandbox Code Playgroud)

选项 2:放弃 dimens.xml

/** Converts dp to pixel. */
val Int.px get() = (this * Resources.getSystem().displayMetrics.density).toInt()
Run Code Online (Sandbox Code Playgroud)
view.updateLayoutParams {
    width = 100.px
    height = 100.px
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*ard 5

我相信您应该使用dimens中定义的dp 值以及getDimensionPixelSize。在自定义视图中,Kotlin 实现如下所示:

val layoutParams = layoutParams
val width = context.resources.getDimensionPixelSize(R.dimen.width_in_dp)
layoutParams.width = width
Run Code Online (Sandbox Code Playgroud)