user3103869
user3103869

Reputation: 41

Android OnTouchListener interferes OnClickListener

I have got an Activity with a function, where I can create a new ImageView. I would like to move the ImageView, so implemented a new OnTouchListener. That is working great, but I would also like to add a LongClickListener and here is my problem:

My LongClickListener starts one time when I am moving the ImageView.

What can I do to fix this?

public ImageView neuesDefaultBild(int x, int y, int id){

    ImageView iv=new ImageView(this);
    iv.setImageResource(R.drawable.usericon);
    iv.setId(id);
    iv.setX(x);
    iv.setY(y);
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.width=180;
    params.height=130;
    iv.setLayoutParams(params);

    iv.setLongClickable(true);
    iv.setFocusable(true);
    iv.setFocusableInTouchMode(true);
    iv.setEnabled(true);

    iv.setOnTouchListener(new View.OnTouchListener(){

        public boolean onTouch(View v, MotionEvent event) {

            boolean defaultResult = v.onTouchEvent(event);

            switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                break;

             case MotionEvent.ACTION_MOVE:

                 //Get the coords from the Event
                    int x_cord = (int) event.getRawX();
                    int y_cord = (int) event.getRawY();

                    v.setX(x_cord-90);
                    v.setY(y_cord-130);

                    return true;
             default:
                    return defaultResult;
             }
            return false;
        }
    });

    iv.setOnLongClickListener(new View.OnLongClickListener() {

        public boolean onLongClick(View v) {

            Toast.makeText(getApplicationContext(), "Long!!", Toast.LENGTH_SHORT).show();

            return false;
        }
    });
    return iv;
}

Upvotes: 4

Views: 1081

Answers (1)

Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

OnclickListener can be set using OnTouchListener itself Just set a flag

    private int boolean onClick;

    switch (event.getAction())
    {
        case MotionEvent. ACTION_DOWN:
        {
               onClick = true;
               break ;
        }
        case MotionEvent. ACTION_MOVE:
        {                 
               onClick = false;                  
               break ;
        }
        case MotionEvent. ACTION_UP:
        {  
               if(onClick)
               {
                   //Call your own click listener 
               }
               break; 
        }  
   }

Upvotes: 5

Related Questions