Dynamically creating Buttons and setting onClickListener

后端 未结 9 970
囚心锁ツ
囚心锁ツ 2020-11-29 22:45

I have problem with handling dynamically created Buttons on Android. I\'m creating N buttons and I have to do the same method when button is clicked but I have to know which

相关标签:
9条回答
  • 2020-11-29 23:13

    Is preferable not to mess up with the ids, setTag and getTag methods were designed for that purpose, it's the fast and clean way to set a bunch of button listeners on a dynamic layout

    This answer may you help: https://stackoverflow.com/a/5291891/2804001

    0 讨论(0)
  • 2020-11-29 23:17

    "This doesn't look good to me" why not? doesn't it work? You could also create a static member variable holding a list of all added buttons, and then look for the clicked button in that list instead.

    0 讨论(0)
  • 2020-11-29 23:18

    I don't know why you would want to create N buttons, it looks like your value of N is greater than 10 at least, if you are not trying to show them all at once (I mean fit all of them into one single screen, no scrolling) you could try to recycle the invisible buttons just like we do for list view using a list view holder. This would reduce your memory footprint and boost performance, and differentiate the buttons based either on the text you set on them or a tag or you can even hold a reference to those small number of buttons.

    0 讨论(0)
提交回复
热议问题