从编程方式添加按钮的OnClick得到()? [英] get OnClick() from programmatically added buttons?

查看:127
本文介绍了从编程方式添加按钮的OnClick得到()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在布局中增加了一些按钮:

i have added some button in a layout:

LinearLayout row = (LinearLayout)findViewById(R.id.KeysList);
    keys=db.getKeys(console);

    my_button=new Button[keys.size()];
    for (bt=0;bt<keys.size();bt++){
           my_button[bt]=new Button(this);
           my_button[bt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));
           my_button[bt].setText(keys.get(bt));
           my_button[bt].setId(bt);
           row.addView(my_button[bt]);
           my_button[bt].setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  if (my_button[bt].getId() == ((Button) v).getId()){
                      Toast.makeText(getBaseContext(), keys.get(bt), 0).show();
                  }
              }
           });
        }

结果我想知道的是点击哪个按钮以及如何获得点击按钮的文字?结果,我想用BT这里剂量似乎没有工作!


I want to know which button is clicked and how to get text of the clicked button?
And I think using bt here dose not seem to work!

推荐答案

这code上。我希望它能帮助您:)

This code is running. I hope it help you :)

    final ArrayList<String> Keys = new ArrayList<String>();
    for(int i = 0; i < 10; i ++){
        Keys.add("Keys is : " + String.valueOf(i));
    }

    LinearLayout Row = (LinearLayout)findViewById(R.id.KeysList);

    final Button[] my_button = new Button[Keys.size()];

    for (int bt = 0; bt < Keys.size(); bt ++){
        final int Index = bt;

        my_button[Index] = new Button(this);
        my_button[Index].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
        my_button[Index].setText(Keys.get(Index));
        my_button[Index].setId(Index);

        my_button[bt].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (my_button[Index].getId() == ((Button) v).getId()){
                    Toast.makeText(getBaseContext(), Keys.get(Index), 0).show();
                }
            }
        });

        Row.addView(my_button[Index]);
    }

ExampleProject ID:您的项目

这篇关于从编程方式添加按钮的OnClick得到()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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