Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle multiple button click listeners

I've two ImageButtons in my layout, "plus" and "minus". I attach a click listener to the "plus" button with a simple toast message in the click function, and it works.

    ImageButton btplus = (ImageButton)findViewById(R.id.btplus);        
    btplus.setOnClickListener( new ImageButton.OnClickListener(){
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "+", Toast.LENGTH_SHORT);
        }
    });

Then i attach a second click listener to the minus ImageButton...

    ImageButton btminus = (ImageButton)findViewById(R.id.btminus);
    btminus.setOnClickListener( new ImageButton.OnClickListener(){
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "-", Toast.LENGTH_SHORT);
        }
    });

...and no more button click works! The "plus" click too stop working.

I've seen a lot of examples on this theme, but i can't see any difference between them (working) and mine.

like image 741
Luca Clavarino Avatar asked Dec 02 '22 01:12

Luca Clavarino


2 Answers

Such as multiple button click listners...

 ImageButton btminus = (ImageButton)findViewById(R.id.btminus);
 btminus.setOnClickListener(this);

 ImageButton btplus = (ImageButton)findViewById(R.id.btplus);
 btplus.setOnClickListener(this);

then your activity want to implements onclicklistener and you get implemented method is:

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btplus:
            Toast.makeText(getApplicationContext(), "Plus is clicked" + "+", Toast.LENGTH_SHORT).show(); 
            break;
        case R.id.btminus:
            Toast.makeText(getApplicationContext(),"Minus is clicked" + "-", Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
        }
    }
like image 123
Samir Mangroliya Avatar answered Dec 18 '22 21:12

Samir Mangroliya


 ImageButton btplus = (ImageButton)findViewById(R.id.btplus);        
    btplus.setOnClickListener( new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "+", Toast.LENGTH_SHORT).show();
        }
    });
like image 26
jazz Avatar answered Dec 18 '22 22:12

jazz