I am doing some android programming. I am adding buttons to a view. Each button has its own behaviour for its onClick function. But the code seems repetitive. For example:
// the view View v = new View(this); // first button Button b1 = new Button(this); b1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // some method body1 } }); v.addView(b1); // second button Button b2 = new Button(this); b2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // some method body2 } }); v.addView(b2); // nth button // ... Is there a more concise way to add buttons to a view like by passing a method body to a method or some other way? For example like:
public void addButton(MethodBody methodBody) { Button b = new Button(this); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { methodBody } }); v.addView(b); } EDIT: So after seeing the suggestions for lambda, is it possible to do something like the below where there is a general method and just take the body as parameter?
public void addButton(MethodBody methodBody) { Button b = new Button(this); b.setOnClickListener(v -> { methodBody } ); v.addView(b); } EDIT 2: I guess we can do this
// general method public void addButton(OnClickListener onClickListener) { Button button = new Button(this); // other stuff button.setOnClickListener(onClickListener); v.addView(button); } // run the method addButton(v -> { // some body });