android - 以编程方式获取按钮数组,无需对 id 进行硬编码并通过 findViewById() 获取它

标签 android layout-inflater findviewbyid r.id

我有一个 XML 布局,顶部有一个 EditText,然后是许多按钮和键盘后面的一堆其他 View 。根元素是 ConstraintLayout

<ConstraintLayout ...>
    <EditText .../>

    <!-- Here is the list of buttons -->
    <!-- For placement constraints purposes, I may have id's in the buttons -->
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A"/>
    ... <!-- About 26 of them -->
    <Button .../>

</ConstraintLayout>

硬编码按钮 id 和 findViewById(resId) 会留下很多样板文件,这似乎不是最好的方法。

如何在 ActivityName.java 中的 Button[] 数组中获取这么多按钮?最好的方法是什么?


编辑:

下面是我在 XML 中使用的单个实际按钮。我认为很难以编程方式将按钮添加到 ConstraintLayout。如果可能,请分享以编程方式进行的方法。

<Button
        android:id="@+id/keyboard_button_Q"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:minWidth="0dp"
        style="?android:attr/buttonBarButtonStyle"
        android:padding="0dp"
        android:text="Q"
        app:layout_constraintEnd_toStartOf="@id/keyboard_button_W"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

最佳答案

创建一个仅包含一个按钮的简单 button.xml 文件。 然后构建你的按钮运行时你想要多少次。这就是 LayoutInflater 类的原因。

Button button = (Button) LayoutInflater.from(this).inflate(R.layout.button, null); 

关于android - 以编程方式获取按钮数组,无需对 id 进行硬编码并通过 findViewById() 获取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46942595/

相关文章:

android - Flutter 应用加载动态库失败

android - 在 onMenuItemActionExpand 上显示 SearchView 内的按钮

android - Android LayoutInflater类的inflate方法中第二个参数怎么用

java - 无法从静态上下文中引用非静态方法 <T>findViewById(int)

Android Activity findviewbyid() 为空

android - android.graphics.Path.finalize() 10 秒后超时的根本原因是什么

android - 下载安卓大文件

带有单选按钮的Android可扩展 ListView

Android 复合 View : cannot make child view match parent

Android:如何在服务类中使用mediaController?