简体   繁体   中英

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;
}

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; 
        }  
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM