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 }); 
1
  • Lambdas. Commented Jun 16, 2019 at 10:39

3 Answers 3

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 } 
Sign up to request clarification or add additional context in comments.

Comments

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 } 

Comments

0

Pass OnClickListener implementation as parameter, read about Strategy Design Pattern

1 Comment

this can be a comment and not an answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.