Search code examples
androidevent-handlingonclicklisteneronlongclicklistenerandroid-event

How can i use OnLongClick Listener on more than 1 buttons in a onLongClick Method in same class


Here is my Code ...

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

        text = (TextView) findViewById(R.id.textView);
        text.setText("Application Created");
        btn1 = (Button) findViewById(R.id.Mybutton);
        btn1.setOnClickListener(this);
        btn2 = (Button) findViewById(R.id.btn2);
        btn2.setOnClickListener(this);
        btn1.setOnLongClickListener(**this**);*(Error Generated here)*
    }

public boolean onLongClick( View v)
{


    return  true;
}

i am trying to use on long click listener on more than two buttons and handle them in a single method (public boolean onLongClick(View v)) by using switch case. I tried my code but their is an error generated when i pass btn1.setOnLongClickListener(this); "this" in the braces" i am handling this event in the same class.


Solution

  • 1) Implement your activity with the interface View.OnLongClickListener 2) Override Boolean method will generate as onLongClick, where you can write your switch case for the buttons. 3) initialize the button with setOnLongClickListener(this) as button.setOnLongClickListener(this);[onCreate]

    Sample as below-

    public class MainActivity extends AppCompatActivity implements View.OnLongClickListener{
    
        private Button btnOne, btnTwo, btnThree;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            btnOne = (Button) findViewById(R.id.idBtnOne);
            btnTwo = (Button) findViewById(R.id.idBtnTwo);
            btnThree = (Button) findViewById(R.id.idBtnThree);
    
            btnOne.setOnLongClickListener(this);
            btnTwo.setOnLongClickListener(this);
            btnThree.setOnLongClickListener(this);
    
        }
    
        @Override
        public boolean onLongClick(View v) {
    
            switch(v.getId()){
                case R.id.idBtnOne:
                    Toast.makeText(MainActivity.this,"Long pressed on Button 1",Toast.LENGTH_LONG).show();
                    break;
                case R.id.idBtnTwo:
                    Toast.makeText(MainActivity.this,"Long pressed on Button 2",Toast.LENGTH_LONG).show();
                    break;
                case R.id.idBtnThree:
                    Toast.makeText(MainActivity.this,"Long pressed on Button 3",Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
    
            }
    
            return false;
        }
    }