简体   繁体   中英

How can I manage onClickListener of a dynamically created button?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM