【问题标题】:Android:How to get the text from the Button when clicked? [duplicate]Android:单击时如何从按钮获取文本? [复制]
【发布时间】:2011-05-05 14:33:38
【问题描述】:

for(i=0;i

        btnAlpha[i] = new Button(this);
        btnAlpha[i].setBackgroundColor(Color.TRANSPARENT);
        btnAlpha[i].setTextColor(Color.GREEN);
        btnAlpha[i].setText(Character.toString ((char)(j+i)));
        btnAlpha[i].setOnClickListener(new View.OnClickListener(){              
            public void onClick(View v){
            //Want to get the text from the current button.
                             btnAlpha[i].getText();
                            //But it gives error that "i" cannot be accessed.

        }});

我得到的错误是“不能引用在不同方法中定义的内部类中的非最终变量”。但我需要在正确的时间得到文本。怎么做?还有其他方法吗? 请帮忙!

【问题讨论】:

    标签: android button android-widget


    【解决方案1】:

    Button 是 View 的子类,因此 onClick 的参数 v 是被点击的 Button。试试

    public void onClick(View v) {
        ((Button) v).getText();
    }
    

    【讨论】:

    • 非常感谢!这解决了问题。
    【解决方案2】:

    在 for 循环中创建一个新变量 final int x = i; 并在 onClick 方法中使用 x 代替 i

    编辑:实际上我不确定这会正常工作。哎呀。 Kype P 的回答看起来不错。

    【讨论】:

      猜你喜欢
      • 2018-01-25
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多