Android:了解以编程方式创建的按钮被按下的按钮
我正在尝试这样做:
以编程方式在布局上创建 4 个按钮。然后,为每个按钮创建一个 onclick 侦听器。然后,根据按下的按钮,将执行一些逻辑。
我在 XML 文件中创建了一个 LinearLayout 并将其命名为“布局”。
所以,我的代码是这样的:
layout = (LinearLayout)findViewById(R.id.layout);
//Create the array of buttons
Button [] subjectButtons_BT = new Button[4];
for(int i=0; i<4; i++){
subjectButtons_BT[i] = new Button(this);
// Add the button to the layout
layout.addView(subjectButtons_BT[i]);
subjectButtons_BT[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// if it is the first button, do LOGIC1
// if it is the second button, do LOGIC2 etc
}
});
}
到目前为止,我已经成功创建了 4 个按钮,并且我可以单击这些按钮。 但是,我不知道 setOnClickListener 部分中的逻辑如何。
我想知道按下的是哪个按钮。因此,我尝试使用 v.getId() 但它总是返回 -1。
有人可以建议这是否是正确的方法吗?如果是这样,逻辑如何?
谢谢。
I am trying to do this:
Programatically create 4 buttons on a layout. Then, create an onclick listener for each of the button. Then, based on which button is pressed, will do some logic.
I have created a LinearLayout in my XML file and called it "layout".
So, my codes go something like this:
layout = (LinearLayout)findViewById(R.id.layout);
//Create the array of buttons
Button [] subjectButtons_BT = new Button[4];
for(int i=0; i<4; i++){
subjectButtons_BT[i] = new Button(this);
// Add the button to the layout
layout.addView(subjectButtons_BT[i]);
subjectButtons_BT[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// if it is the first button, do LOGIC1
// if it is the second button, do LOGIC2 etc
}
});
}
So far, I have managed to create the 4 buttons and I can click on the buttons.
However, I do not know how to the logic in the setOnClickListener part.
I wanted to know which button is pressed. So, I tried using v.getId() but it always returns a -1.
Can someone advise if this is the right way to go? And if so, how to do the logic?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有两个选项来识别单击了哪个动态按钮。
1)您可以为按钮设置id,在
onClick()
方法中您可以通过button.getId()
方法获取id,您可以比较id并根据点击。2)如果你设置了标签,那么你必须通过调用
button.getTag()
方法来获取标签,这样你就可以通过按钮传递对象You have two options for identify which dynamic button is clicked.
1) You can set id to the button and in
onClick()
method you can get id bybutton.getId()
method and you can compare ids and perform action according to click.2) If you set tag then you have to get tag by calling
button.getTag()
method and by this way you can pass object with the button您可以在创建按钮后设置按钮的 id,然后在 OnClickListener 中检查该 id
You can set the id of the buttons after you create them, and then check for that id within the OnClickListener