---------------------------------------华丽的分割线-----------------------------------------
Resources resources = getResources();
float fPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, resources.getDisplayMetrics());
// 同理 px转dip:
// float fDip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 300, resources.getDisplayMetrics());
// int iDip = Math.round(fDip);
int iPx = Math.round(fPx);
EditText editText = new EditText(this);
editText.setWidth(iPx);
editText.setHeight(LayoutParams.WRAP_CONTENT);
// 或者
// LayoutParams layoutParams = new LayoutParams(iPx, LayoutParams.WRAP_CONTENT);
// editText .setLayoutParams(layoutParams);
注:有时直接使用setWidth等不起作用,可以使用LayoutParams 设置。
本文介绍在Android开发中如何将DIP单位转换为PX单位,并提供了具体的代码实现示例。同时,还讨论了在某些情况下直接设置宽度可能不生效的问题及解决办法。

被折叠的 条评论
为什么被折叠?



