android - 基于现有布局以编程方式添加按钮

标签 android android-layout android-button

根据this post ,可以在java中以编程方式添加按钮。

我想根据布局构建按钮。这可能吗?

例如,

<!-- btn.xml-->
<Button
    android:id="@+id/button_id"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="4dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="4dp"
    android:minHeight="60dp"
    android:onClick="myFunction"
    android:textAllCaps="false" />

在我的java代码中,我在字符串列表上构建按钮,如下所示:

final LinearLayout layout = findViewById(R.id.my_layout);
for(String label : stringList){
    Log.d("BTN_ITERATION", "for label : " + label);
    Button btn = new Button(getApplicationContext());
    btn.setText(label);
    layout.addView(btn);
}

对于每个按钮迭代,我想设置一个 btn.xml 布局。

我想过这样的事情,但我不知道:

button = (button) View.inflate(this, R.layout.btn, null);
layout.addView(button);

谢谢! ;)

最佳答案

参见this similar question with answer .

试试这个:

Button btn = (Button) inflater.inflate(R.layout.btn, layout, false);

关于android - 基于现有布局以编程方式添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55503814/

相关文章:

android - 在我的 mac 进入休眠状态后,adb 无法识别我的 android 设备

android - 如何从 Android 的 json 中的任何 url 获取响应,而不是在响应之后我想解析它

java - 编辑 xml 元素的 "app"属性

Java Android - 在方法内部定义新的类函数?

android - SSL 证书 : "No peer certificate" 问题

android - 查找放置在 TextView 上的字母的坐标

android - 根据项目设置 ListView 高度可在 Android Nougat 设备的末尾提供额外的空间

java - 我的应用程序在单击按钮启动 Activity 时崩溃,但可以在模拟器中运行

android:button ="@null"不适用于较低的 API <= 19 设备

android - 如何自定义切换按钮?