views:

700

answers:

2

onClick never fires! Why not? Please help.

    for(int i = 0; i < 12; i++)
    {


        String title = "Button" + i;
        Button sliderButton = new Button(this);
        sliderButton.setText(title);
        glideMenuTray.addView(sliderButton,100,40);

        sliderButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d("gm", "Tapped ");
            }
        });

    }
A: 

If you are using Donut or Eclair, you can use common click listener, registered in your Activity and hooked with your buttons in the layout XML.

For reference, look here, the category Easier click listeners.

Dimitar Dimitrov
I don't think that method for Easier click listeners will work, since his Buttons are dynamic, not pre-defined in XML.
Klondike
+2  A: 

I'm no expert at stuff like this, but it's probably something to do with garbage collection, and the OnClickListeners passing out of scope.

Though I don't think you can use the super-easy approach to onClickListeners that Dimitar mentions, you can probably use the middle approach that the section he links to discusses, even though it's not a new approach. To repeat the example code here, it's:

View.OnClickListener handler = View.OnClickListener() {
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.myButton: // doStuff
                break;
            case R.id.myOtherButton: // doStuff
                break;
        }
    }
}

findViewById(R.id.myButton).setOnClickListener(handler);
findViewById(R.id.myOtherButton).setOnClickListener(handler);

If the only thing distinguishing the buttons is their title text, well, you could use that to distinguish between them in the master onClick method.

Klondike