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

时间:2017-10-25 21:49:06

标签: android layout-inflater findviewbyid r.id

我有一个XML布局,顶部有一个EditText,然后是键盘后面的很多按钮和一堆其他视图。根元素是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)会留下很多样板,而且似乎不是最好的方式。

如何在Button[]的{​​{1}}数组中获取这么多按钮?最好的方法是什么?

编辑:

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

ConstraintLayout

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您可以使用android:tag

将数字与视图相关联
  

<强>机器人:代码

     

为此视图提供包含字符串的标记,稍后将使用View.getTag()检索或使用View.findViewWithTag()进行搜索。通常最好使用ID(通过android:id属性)而不是标签,因为它们更快并允许编译时类型检查。

     

可以是字符串值,使用'\;'转义unicode字符的'\ n'或'\ uxxxx'等字符;

有了这个,您可以记住布局中的所有按钮:

<Button 
    android:layout_width="wrap_content"
    android:tag="0"
    android:layout_height="wrap_content"
    android:text="A"/>

<Button 
    android:layout_width="wrap_content"
    android:tag="1"
    android:layout_height="wrap_content"
    android:text="B"/>

 ...

然后,您可以使用findViewWithTag()和for循环获取所有按钮:

Button[] buttons = new Button[26];

for(int i = 0; i < 26; i++) {
  buttons[i] =  findViewByTag(String.valueOf(i));
}

对于点击监听器,您可以通过使用getTag()检查标记来执行某些操作:

buttonClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      int tag = Integer.parseint(v.getTag());

      // do something based on the tag.
    }
};

答案 2 :(得分:0)

你可以看看的一件事是Android的Butter刀库。您只需使用@BindView和视图ID注释字段,Butter knife将自动在您的布局中投射相应的视图。在我看来,这是一个很好的方法,因为你仍然可以在布局XML文件中有一个清晰的结构。

以下是如何在您的应用中使用它的示例

 @BindView(R.id.title) TextView title;
 @BindView(R.id.subtitle) TextView subtitle;
 @BindView(R.id.footer) TextView footer;

要在项目中包含Butter knife,您只需将依赖项添加到app gradle文件即可。

compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

有关详细信息和详细的安装和使用指南,您可以查看他们的网站: http://jakewharton.github.io/butterknife/