簡體   English   中英

如何在dp值中設置Layoutparams的高度/寬度?

[英]How to set Layoutparams height/width in dp value?

我嘗試在按鈕中手動設置高度/寬度,但沒有用。 然后實現了Layoutparams。 但是 size 顯示很小並且沒有獲得所需的 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);
.
.
  ViewGroup.LayoutParams params = ListView.getLayoutParams();
        params.height = (int) (50 * customsDebts.size() * (getResources().getDisplayMetrics().density));
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        ListView.setLayoutParams(params);

我相信您應該使用在維度中定義的dp 值以及getDimensionPixelSize 在自定義視圖中,Kotlin 實現如下所示:

val layoutParams = layoutParams
val width = context.resources.getDimensionPixelSize(R.dimen.width_in_dp)
layoutParams.width = width

選項 1:使用 dimens.xml

view.updateLayoutParams {
    width = resources.getDimensionPixelSize(R.dimen.my_width)
    height = resources.getDimensionPixelSize(R.dimen.my_height)
}

選項 2:免除 dimens.xml

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM