0

Given N widgets of the same 'kind' (intentionally avoiding the class or type terms here for avoiding confusion), I'd like to assign the same event listener to all of them in an idiomatic way.

For clarity, it'd be something akin to $(".foo").click(...); in jQuery. Notice the class selector.

Right now I can code it in a fairly concise way, but I was wondering whether there is an specific mechanism in Android for achieving this.

Update - example:

    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    ...
    buttonN = (Button) findViewById(R.id.buttonN);

    buttons = new Button[]{button1, button2, ..., buttonN};

    // Pretty imperative.
    // Would't it be better to specify that all buttons belong to the same 'kind',
    // and set a listener to that 'kind'?
    for (int i = 0; i < buttons.length; i++)
        buttons[i].setOnClickListener(...);
4

0 回答 0