动态创建按钮和设置onClickListener [英] Dynamically creating Buttons and setting onClickListener
问题描述
我有问题,处理动态创建按钮在Android上。我创建N个按钮和我做同样的方法被点击按钮的时候,但我必须知道被点击的按钮。
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 button is clicked.
for (int i = 0; i < NO_BUTTONS; i++){
Button btn = new Button(this);
btn.setId(2000+i);
...
btn.setOnClickListener((OnClickListener) this);
buttonList.addView(btn);
list.add(btn);
Cucurrently我加入ID为每一个按钮,我用下面的方法,看哪个按钮被点击。 (行 btn.setId(2000 + I);
和 btn.setOnClickListener((OnClickListener)本);
)。这种方法也可以实现在活动。
Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i);
and btn.setOnClickListener((OnClickListener) this);
). This method is also implemented in the activity.
@Override
public void onClick(View v) {
switch (v.getId()){
case 2000: selectButton(0);
break;
...
case 2007: selectButton(7);
break;
}
}
这看起来并不好我,所以我要问有没有一些更好的方式来做到这一点?或如何发送一些信息给onclick事件?有什么建议?
This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?
推荐答案
您可以创建一个返回onclickListener,并采取一个按钮作为参数的方法。然后使用该方法来设置onClicklistener在你的第一个循环。
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..
更新:code可能是soemthing沿着这些路线:
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));
这篇关于动态创建按钮和设置onClickListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!