Desthstro Desthstro - 4 months ago 12
Java Question

Adding multiple on click listeners for several buttons

How can you make it so that user can have several buttons with on click listeners. I tried it with 2 buttons, but it said that I had already defined the on-click listener so I could not make another on click listener as a result. The code I have so far is:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

private View btnRender;
private LinearLayout container;
private View btnRendered;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnRender = (View)findViewById(R.id.btn_render);
container = (LinearLayout)findViewById(R.id.fragment_layout);
btnRendered = (View) findViewById(R.id.btn_rendered);

//set event handling for button
btnRender.setOnClickListener(onClickListener());
}

private View.OnClickListener onClickListener() {


return new View.OnClickListener() {
@Override
public void onClick(View v) {
//replace fragment when clicked
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_layout, new PDFRenderFragment());
ft.commit();

//gone button after all
btnRender.setVisibility(View.GONE);
container.setVisibility(View.VISIBLE);
}
};


}
}


The
btn_rendered
is the other button that I want to set an on click listener for, but the software will not let me do this. Is it true that I need to set up a switch-case method for it to work?

I just tried out both codes and none of them seem to have doen the desired effect. Now whenever I click one of the buttons, the 2nd pdf always shows! (what I was using the button for)

Answer

You can handle like below.

btnRender.setOnClickListener(onClickListener()); 
btnRendered.setOnClickListener(onClickListener());

 private View.OnClickListener onClickListener() {


        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch(v.getId()){
                case R.id.btn_render:
                //replace fragment when clicked
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.fragment_layout, new PDFRenderFragment());
                ft.commit();

                //gone button after all
                btnRender.setVisibility(View.GONE);
                container.setVisibility(View.VISIBLE);
                break; 
                case R.id.btn_rendered:
                // your logic here 

                break; 
            }
          }
        };
    }