Android Dynamically Created Button: setOnClickList

2019-06-23 22:34发布

问题:

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

回答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.



回答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



回答3:

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.



回答4:

Am I right in assuming that the following line:

glideMenuTray.addView(sliderButton,100,40);

Adds the view to the coords x:100,y:40 onto some View extending ViewGroup?

In that case you are stacking 12 buttons on top of each other, only the last Button (labeled Button11) will be visible (and clickable).

And provided that the question is 3 years old I really hope you already resolved this by now :)



回答5:

set the setOnClickListener before adding the view.

for(int i = 0; i < 12; i++) {
    String title = "Button" + i;
    Button sliderButton = new Button(this);
    sliderButton.setText(title);
    sliderButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d("gm", "Tapped ");
        }
    glideMenuTray.addView(sliderButton,100,40);
}