安卓:点击后如何从按钮上的文本?按钮、文本

2023-09-06 22:14:45 作者:薄年

有关(i = 0; I< 26;我++){

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.

        }});

我得到的错误是不能指非final的变量在不同的方法中定义的内部类里面。但我需要得到那个正确的时间的文本。怎么做?是否有任何其他方式做到这一点?请帮助!

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!

推荐答案

按钮是查看的子类,所以参数的onClick,V,是被点击的按钮。尝试

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