Android:How to get the text from the Button when clicked? [duplicate]

我是研究僧i 提交于 2019-12-23 02:58:36

问题


for( i=0; i<26; 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.

        }});

The error i get is "cannot refer to a non-final variable inside an inner class defined in a different method". But i need to get the text at that right time. How to do it? Is there any other way to do it? Please Help!


回答1:


Button is a subclass of View, so the argument to onClick, v, is the Button being clicked. Try

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



回答2:


create a new variable final int x = i; in the for loop and use x in place of i in the onClick method

edit: actually im not sure this will work correctly. oops. Kype P's answer looks pretty good.



来源:https://stackoverflow.com/questions/4106198/androidhow-to-get-the-text-from-the-button-when-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!