How can I manage onClickListener of a dynamically created button?

Mehak :

I'm trying to create 'n' buttons based on the option user has selected. 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. It gives the error "Variable used in lambda expression should be final or effectively final". 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. I'm trying to get the value from the list and update it on Firebase. How can I achieve this, any help is greatly appreciated.

alainlompo :

in Java you can't use non-final (and also non-effectively-final) variables in lambda as well as in anonymous inner classes.

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.

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.

Now you can change the binding to the clickListener event handler to look like:

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=291635&siteId=1