2

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
        });
Questionerer
  • 91
  • 1
  • 11
  • [Lambdas](https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html). – Turing85 Jun 16 '19 at 10:39

3 Answers3

2

Use Java 8 Lamdas:

b1.setOnClickListener((View v) -> {
    // // some method body1
});

b2.setOnClickListener((View v) -> {
    // // some method body2
});

To enable this in Android Studio add the following code block inside build.gradle (app)

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
Prokash Sarkar
  • 11,723
  • 1
  • 37
  • 50
1

You can use Java 8's method references.

void onCreate(){
    //...
    findViewById(R.id.btn1).setOnClickListener(this::handleBtn1Click);
    findViewById(R.id.btn2).setOnClickListener(this::handleBtn2Click);
    findViewById(R.id.btn3).setOnClickListener(this::handleBtn3Click);
}

void handleBtn1Click(View view){
    // handle btn1 click here
}

void handleBtn2Click(View view){
    // handle btn2 click here
}

void handleBtn3Click(View view){
    // handle btn3 click here
}
frogatto
  • 28,539
  • 11
  • 83
  • 129
0

Pass OnClickListener implementation as parameter, read about Strategy Design Pattern