android - 如何为 inflatedView (按钮)设置动态宽度和高度

标签 android android-layout layout-inflater

我有一个 Activity ,我可以使用 LayoutInflater 在其上以编程方式创建一些按钮,如下所示:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Button newButton = (Button) inflater.inflate(R.layout.my_button, currentTableRow, false);

和 my_button.xml:

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/newButton"
android:layout_width="30dp"
android:layout_height="30dp"</Button>

它工作正常。但我的问题是:有没有什么方法可以将宽度和高度传递给 my_button.xml,或者有什么方法可以在我想膨胀该 View 时设置宽度和高度。我的意思是有时我想设置“30dp”,有时将其设置为“45dp”等。提前致谢。

最佳答案

float scale = context.getResources().getDisplayMetrics().density;

button.getLayoutParams().height = 30 * scale;
button.getLayoutParams().width = 30 * scale;

通过使用上面的代码,可以简单地在“dp”中设置高度和宽度。

关于android - 如何为 inflatedView (按钮)设置动态宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37877559/

相关文章:

android - 调用 AudioRecord.start() 时出现 IllegalStateException

android - 将 v21 中的 AppCompatButton 设置为没有阴影和角半径为零

android-layout - 如何在 ICS 样式的 EditText 中更改线条的颜色

java - 警报对话框的 inflated layout 不起作用

android - 在 inflated layout 中使用 setText() 到 TextView() 后不显示文本

android - 如何在不推送内容的情况下折叠 AppBarLayout 动画,类似于 WhatsApp Android?

android - Flutter Android 透明导航栏和按钮

android - 如何获取包括 subview 在内的布局中的 View 总数

android - RecyclerView 滚动和高度调节问题

android - 膨胀的框架布局上的按钮未触发点击事件