动态创建按钮并设置 onClickListener [英] Dynamically creating Buttons and setting onClickListener

查看:27
本文介绍了动态创建按钮并设置 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);

目前我正在为每个按钮添加 ID,我正在使用下面的方法查看点击了哪个按钮.(行 btn.setId(2000+i);btn.setOnClickListener((OnClickListener) this);).活动中也实现了这个方法.

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

更新:代码可能是这样的:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆