简体   繁体   中英

ANDROID Handle large amount of buttons with array?

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

You can't do what you proposed in your solution. A better way to go about it is to add the buttons dynamically in code. For instance,

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;
}

User "Horschtele" answered it in a perfect way but he deleted his answer on his own (don't know why).

Horschtele, if you read that, I just want to say that this solution is just perfect!

I have to (or at least I think I have to) do this for every tableRow but this saves me an infinite amount of time. Thanks again Horschtele (are you german? :))

My modified version of Horschtele's answer if you already have your buttons in a table:

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);
            }

(don't wonder about the println, you can easily check if the system correctly recognizes the container you are refering to).

If you did it my way with an array of Button then this is the way to go:

button[i] = (Button)container.getChildAt(i);
button[i].setOnTouchListener(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM