【问题标题】:Inner class - final variable can't be looped?内部类 - 最终变量不能循环?
【发布时间】:2015-10-27 16:27:12
【问题描述】:

我正在尝试创建一个循环,为每个按钮提供一个方法,该方法的参数取决于它是什么按钮。我不断收到错误:

i 不是最终变量 - 如果嵌套在内部类中,则必须是。

for (int i = 0; i < 14; i++) {
    buttons[i].setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            // issue is with i value here
            move.makeMove(move.cups.get(i);
            updateButtons();
        }
    });
    currentCup = nextCup;
}

【问题讨论】:

    标签: java android nested inner-classes


    【解决方案1】:

    试试这个方法:

    for (int i = 0; i < 14; i++) {
        final int currentI = i;
        buttons[i].setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                // issue is with i value here
                move.makeMove(move.cups.get(currentI);
                updateButtons();
            }
        });
        currentCup = nextCup; 
    }
    

    【讨论】:

    • 这很奇怪 - 我以前试过这个但没有用 - 一定是语法错误......谢谢
    • @JossMillerTodd 您可能已经在侦听器内部而不是外部声明了最终变量。或者在 for 循环中。
    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    相关资源
    最近更新 更多