首页 > 解决方案 > 如何使按钮使用现有布局

问题描述

我是 android 新手,并且在很长一段时间内都在为以下问题苦苦挣扎。我在 for 循环中创建了几个按钮。在 res\layout 下,我创建了我想要的按钮外观。是否可以使按钮使用该布局,因为在编辑器中很容易修改它?目前我正在使用 LayoutParams 并通过调用相应的方法来设置所有内容(仅在下面的示例中设置文本“push me”)。

这是我的 MainActivity.java 文件中的代码:

for(int i = 0; i<50; i++) {
            Button myButton = new Button (this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            myButton.setLayoutParams(params);
            myButton.setText("Push Me");
            LinearLayout ll = findViewById(R.id.myLayout);
            ll.addView(myButton);
        }

这是我希望按钮使用的 buttonlayout.xml 的内容:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/buttonidd">

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

我还想以这种方式创建的每个按钮的 ID 更改为“i”。提前致谢!

标签: android

解决方案


可以使用 RecyclerView 轻松创建大量类似的组件,对手机来说效果更好。因为 ViewHolder。

如果您需要的组件数量不是很多,并且您想在您的情况下动态调整组件的位置,请注意您的布局使用ConstraintLayout,所有动态调整的组件都必须设置约束。


推荐阅读