[英]How can I manage onClickListener of a dynamically created button?
I'm trying to create 'n' buttons based on the option user has selected.我正在尝试根据用户选择的选项创建“n”按钮。 The buttons can range from 1 to 3. However I'm having difficulty when I try to update the variable depending upon the button pressed.按钮的范围可以从 1 到 3。但是,当我尝试根据按下的按钮更新变量时遇到了困难。 It gives the error "Variable used in lambda expression should be final or effectively final".它给出了错误“lambda 表达式中使用的变量应该是最终的或有效的最终”。 I understand the error but can't figure out how I can resolve this issue.我理解错误,但不知道如何解决此问题。 Here is my sample code:这是我的示例代码:
for (int i = 0; i < options; i++) {
Button button = new Button(this);
button.setId(position);
buttons[i] = button;
buttons[i].setOnClickListener(v -> {
tempToMaintain.setValue(listParameters.get(i));
});
}
'options' contain the number of buttons to create, tempToMaintain is a variable that is referenced from Firebase. 'options' 包含要创建的按钮数量,tempToMaintain 是一个从 Firebase 引用的变量。 I'm trying to get the value from the list and update it on Firebase.我正在尝试从列表中获取值并在 Firebase 上更新它。 How can I achieve this, any help is greatly appreciated.我怎样才能做到这一点,非常感谢任何帮助。
in Java you can't use non-final (and also non-effectively-final ) variables in lambda as well as in anonymous inner classes.在 Java 中,您不能在 lambda 以及匿名内部类中使用非最终(以及非有效最终)变量。
You could get rid of the lambda expression by creating a class that implements the View.OnClickListener
interface and give it the variable i as a constructor parameter.您可以通过创建一个实现View.OnClickListener
接口的类并View.OnClickListener
提供变量i作为构造函数参数来摆脱 lambda 表达式。
for example:例如:
class MyButtonClickListener implements View.OnClickListener {
private int parameterIndex;
public MyButtonClickListener(int parameterIndex) {
this.parameterIndex = parameterIndex;
}
public void onClick(View v) {
tempToMaintain.setValue(listParameters.get(parameterIndex));
}
}
And that should be it.应该就是这样。 Pass tempToMaintain and listParameters as constructor parameters (just like we did with parameterIndex ) if your new class instances cannot contextually access them.如果您的新类实例无法在上下文中访问它们,则将tempToMaintain和listParameters作为构造函数参数传递(就像我们对parameterIndex所做的一样)。
Now you can change the binding to the clickListener event handler to look like:现在您可以将绑定更改为 clickListener 事件处理程序,如下所示:
for (int i = 0; i < options; i++) {
Button button = new Button(this);
button.setId(position);
buttons[i] = button;
buttons[i].setOnClickListener(new MyButtonClickListener(i));
}
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.