Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setOnClickListener and setOnLongClickListener call on single button issue

I need your help if any one can be, it will be great thing for my solution. I don't know is it possible or not, but I want to try to fix this out any how.. Actually I want to implement two method on single button click event, its simple click and long click, here my code ::

homebutton = (ImageButton) findViewById(R.id.home_icon);
homebutton.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
        Intent intent = new Intent(context, MainActivity.class);
        startActivity(intent);
    }
});
homebutton.setOnLongClickListener(new OnLongClickListener() {
    public boolean onLongClick(View arg0) {
        Toast.makeText(getApplicationContext(), "Long Clicked " , Toast.LENGTH_SHORT).show();
        return false;
    }
});

So, here i am getting something wrong, even single click is working perfectly, and long click is also working, but problem is that after long click event its also start MainActivity as defined in above code of onClick method..

That should not be done, return false is also there, still not working as i want.. So, anybody please help me to get it resolve..

Thanks in Advance..

like image 803
jt. Avatar asked Nov 20 '12 09:11

jt.


People also ask

Which function is used for long press on Android?

Long pressing lets you get some information, download photos from the web, edit pictures, and more.

Which are the ways to set OnClickListener for button in Android?

To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

How does setOnClickListener work?

In Android, the OnClickListener() interface has an onClick(View v) method that is called when the view (component) is clicked. The code for a component's functionality is written inside this method, and the listener is set using the setOnClickListener() method.

Why my setOnClickListener is not working?

You need to put the setOnClickListener in one of the activity callbacks. In your onCreate() method, move the button there and then setOnClickListener() . Show activity on this post.


1 Answers

I believe you need to return TRUE in your onLongClick method - telling the framework that the touch event is consumed and no further event handling is required.

homebutton.setOnLongClickListener(new OnLongClickListener() {
    public boolean onLongClick(View arg0) {
        Toast.makeText(getApplicationContext(), "Long Clicked " ,
              Toast.LENGTH_SHORT).show();

        return true;    // <- set to true
    }
});
like image 50
waqaslam Avatar answered Oct 02 '22 10:10

waqaslam