我有一个安卓应用程序,其中有很多按钮,但这些按钮是在运行时创建的。如果我设置宽度button.setwidth(300)
,它将把宽度设置为300px。我想要宽度以dp为单位设置。有没有什么解决方法?
你需要使用TypedValue.applyDimension
来获取dp的像素数量。这是一个示例:
DisplayMetrics dm = getResources().getDisplayMetrics();
float dpInPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DP, 300, dm);
这将以编程方式提供300dp的像素值。
干杯
Android没有单独的方法来设置按钮在dp中的尺寸。您需要:
//Find screen density scale factor
final float scale = getContext().getResources().getDisplayMetrics().density;
myButton.setWidth((int)(100 * scale));
myButton.setHeight((int)(50 * scale));
没有setWidth(300dp)的方法。解决方法是获取显示大小,并相应地调整300px变量。
我必须说,可能有更好的方法来创建漂亮的布局。您尝试过使用嵌套的线性布局和layout_weights吗?