Android Dynamically Created Button: setOnClickListener doesn't work

25,584

Solution 1

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.

Solution 2

Also, not shure, I once had a problem like that on a TextView and it was because I didnt add setClickable(true)

My code was something like

TextView text = new TextView(this);
text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
text.setText("***");
text.setClickable(true);

text.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        //My action
    }
});

myViewGroup.addView(text );

Hope this helps

Share:
25,584
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    The onClick never fires! Why not? Please help me.

    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 ");
            }
        });
    }
    
  • Eric Mill
    Eric Mill over 14 years
    I don't think that method for Easier click listeners will work, since his Buttons are dynamic, not pre-defined in XML.
  • gardarh
    gardarh over 11 years
    Stuff is not garbage collected unless it is not reachable via any gc root. The OP's code creates buttons that are added to glideMenuTray which is presumably referenced by something (e.g. an Activity) which is reachable from a gc root and therefore the garbage collection argument makes no sense.