开发者

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

开发者 https://www.devze.com 2023-01-23 10:41 出处:网络
This question already has answers here: Get text from pressed button (8 answers) Closed 9 years ago. for( i=0; i<26; i++){
This question already has answers here: Get text from pressed button (8 answers) Closed 9 years ago.
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.
            
    }});

I get the error "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?


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();
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号