ANDROID是否可以使用数组处理大量按钮?

ANDROID是否可以使用数组处理大量按钮?,android,android-button,Android,Android Button,嘿,我正在制作一个android应用程序,它将有大约256个按钮。 因为我不想为所有这些编写完全相同的代码,所以我认为通过阵列实现更简单的解决方案是可能的。我在onCreate中设置侦听器的方法是: 1 for (int i=1; i<32; i++) 2 { 3 button[i] = (Button)findViewById(R.id.button[i]); 4 button[i]

嘿,我正在制作一个android应用程序,它将有大约256个按钮。 因为我不想为所有这些编写完全相同的代码,所以我认为通过阵列实现更简单的解决方案是可能的。我在onCreate中设置侦听器的方法是:

1    for (int i=1; i<32; i++)
2               {
3                   button[i] = (Button)findViewById(R.id.button[i]);
4                   button[i].setOnTouchListener(this);
5               }
1 for(inti=1;i用户“Horschtele”以完美的方式回答了这个问题,但他自己删除了他的答案(不知道为什么)

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);
            }
用户“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);
            }

你不能按照你在解决方案中提出的去做。更好的方法是在代码中动态添加按钮。比如说,

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;
}
View parentView=(LinearLayout)findviewbyd(R.id.parentView);
//在上面声明按钮数组

对于(int i=1;i您不能按照您在解决方案中提出的方法执行。更好的方法是在代码中动态添加按钮。例如

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;
}
View parentView=(LinearLayout)findviewbyd(R.id.parentView);
//在上面声明按钮数组

对于(int i=1;i你不能这样做。你最好使用动态添加按钮。真的吗?该死..你的意思是我应该在代码中添加所有按钮吗?会有区别吗?我害怕重新编写我的整个代码,只是为了注意到我再次面临同样的问题。你不能这样做。最好使用动态添加按钮.真的吗?该死..你的意思是我应该在我的代码中添加所有按钮吗?会有区别吗?我害怕重新编写我的整个代码,仅仅是为了注意到我再次遇到同样的问题。谢谢你的回答,但我真的这样做了,它真的很有效-应该有什么问题吗?如果你不这样做,我可以将代码发送给你我不相信我。我不想像你说的那样添加按钮,因为我在使用这些按钮时有不同的图像,我认为通过XMLThank做起来更容易谢谢你的回答,但我真的这样做了,它真的很有效-应该有什么错?如果你不相信我,我可以给你发送代码。我不想做广告我喜欢你说的按钮,因为我使用的这些按钮有不同的图像,我认为通过XML做起来更容易