Dynamically creating Buttons and setting onClickListener

后端 未结 9 1009
囚心锁ツ
囚心锁ツ 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:06

    You could create a method that returns an onclickListener and takes a button as a parameter. And then use that method to set the onClicklistener in the first loop you have..

    Update: code could be soemthing along these lines:

    View.OnClickListener getOnClickDoSomething(final Button button)  {
        return new View.OnClickListener() {
            public void onClick(View v) {
                button.setText("text now set.. ");    
            }
        };
    }
    

    as a method in the activity and then use it in the loop like this

    button.setOnClickListener(getOnClickDoSomething(button));
    

提交回复
热议问题