如何使用for循环和ArrayList的内容设置多个按钮的文本-Java-Android

问题描述

我目前有35个按钮,最终产品不会使用所有按钮。 我还有一个包含各种项目的arraylist:

ArrayList textBlobs = new ArrayList();
textBlobs.add("text");
textBlobs.add("two");
textBlobs.add("tt");
textBlobs.add("txt");
textBlobs.add("te");
textBlobs.add("tet");
textBlobs.add("go");
textBlobs.add("eat");
textBlobs.add("spring");
textBlobs.add("rolls");
textBlobs.add("egu77$");

我还有35个名为buttonx的按钮,其中x是数字0到34(共35个)

private Button button0,button1,button2,button3,button4,button5,button6,button7,button8,button9,button10,button11,button12,button13,button14,button15,button16,button17,button18,button19,button20,button21,button22,button23,button24,button25,button26,button27,button28,button29,button30,button31,button32,button33,button34;

这些按钮已经使用root.findByViewId(R.id.button_)进行了初始化和声明

在这里我有一个for循环,该循环仅通过textBlobs ArrayList运行。截至目前,所有按钮都没有文本(“”)。我想使用此for循环将通过textBlobs.size()设置的按钮0设置为该索引处textBlobs中包含的文本。

for(int i = 0; i < textBlobs.size(); i++ ) {

        }

并非所有按钮都将被使用,这是目标,它应该能够与长度不超过35的ArrayList一起使用。我对如何设置文本感到困惑。据我所知,设置按钮文本的唯一方法是使用

button0.setText("insert text");

在我的情况下不起作用,因为我无法在for循环的每个实例之间更改名称的数字部分。

有人知道我如何实现我的目标吗?

解决方法

应该使用Button数组的最佳解决方案

ArrayList<Button> btns = new ArrayList<Button>();
,

您只需将所有按钮添加到ArrayList并使用它即可。