1

Hey I am making an android app that will have ~256 buttons. Because I dont want to write the very same code for everyone of these I thought it might be possible to realize an easier solution via arrays. My approach in the onCreate to set the listeners was:

1    for (int i=1; i<32; i++)
2               {
3                   button[i] = (Button)findViewById(R.id.button[i]);
4                   button[i].setOnTouchListener(this);
5               }

I set the Button[] like that: Button[] button=new Button [64];

Now, eclipse tells me in line 3 "button cannot be resolved or is not a field" and it just underlines the word "button", so I think it ignores/just does not recognize the [i] (array)-stuff.

The rest of my code seems to get on with that perfectly because it gets recognized as an object (correct me if I said that wrong) but the findViewById() doesn't get on with it ..

Thanks for the replies, Alex

4

2 回答 2

1

您无法执行您在解决方案中提出的建议。一个更好的方法是在代码中动态添加按钮。例如,

View parentView = (LinearLayout) findViewById(R.id.parentView);
// declare button array above
for (int i=1; i<32; i++)
{
    Button btn = new Button(context);
    // EDIT: adding a background resource
    btn.setBackgroundResource(R.layout.button_layout);
    btn.setText("This is my text");
    btn.setOnTouchListener(this);
    button[i] = btn;
}
于 2013-07-26T15:15:58.417 回答
0

用户“Horschtele”以完美的方式回答了它,但他自己删除了他的答案(不知道为什么)。

Horschtele,如果你读到了,我只想说这个解决方案非常完美!

我必须(或至少我认为我必须)为每个 tableRow 执行此操作,但这可以为我节省无限的时间。再次感谢 Horschtele(你是德国人吗?:))

如果您已经在表格中放置了按钮,我会修改 Horschtele 的答案:

ViewGroup container = (ViewGroup) findViewById(R.id.tableRow1);

            for(int i=0; i<container.getChildCount();i++){
                System.out.println(container.getChildCount());
            Button button = (Button)container.getChildAt(i);
            button.setOnTouchListener(this);
            }

(不要怀疑println,您可以轻松检查系统是否正确识别您所指的容器)。

如果您使用 Button 数组按照我的方式进行操作,那么这就是要走的路:

button[i] = (Button)container.getChildAt(i);
button[i].setOnTouchListener(this);
于 2013-07-26T15:01:07.463 回答