简体   繁体   中英

onTouch giving strange results in getX android

I am trying to move a image when you touch on it. I realize that when I was moving the image makes strange things (it sometimes do it well and others move to different places). I made a Log.d with the getX value and this is what I get:

 03-16 19:26:23.569: D/eventX:(15450): 23.0
 03-16 19:26:23.599: D/eventX:(15450): 91.0
 03-16 19:26:23.629: D/eventX:(15450): 20.0
 03-16 19:26:23.659: D/eventX:(15450): 89.0
 03-16 19:26:23.689: D/eventX:(15450): 17.0
 03-16 19:26:23.719: D/eventX:(15450): 87.0
 03-16 19:26:23.749: D/eventX:(15450): 14.0
 03-16 19:26:23.779: D/eventX:(15450): 85.0
 03-16 19:26:23.809: D/eventX:(15450): 11.0
 03-16 19:26:23.839: D/eventX:(15450): 83.0
 03-16 19:26:23.879: D/eventX:(15450): 8.0

As you can see one is the good value (the value of the position that I touch it) and other that has no sense. Someone knows the reason why?

Here is the peace of code that I am using...

  head.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent ev) {
            // TODO Auto-generated method stub
            switch (ev.getAction()) {


            case MotionEvent.ACTION_MOVE: {
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(head.getLayoutParams().width, head.getLayoutParams().height);
                Log.d("eventX:", ((Float)ev.getX()).toString());
                layoutParams.leftMargin = (int) ev.getX();
                head.setLayoutParams(layoutParams);
                count = false;

                break;
            }

Using the typical getX() function is completely tied to specific view that dispatched the MotionEvent and returns a coordinate relative to that view. In your case it seems likely that multiple views are dispatching the event and you are getting multiple unexpected values.

In any case, using getRawX() will allow you to get a consistent and absolute coordinate, and will resolve the confusion of all the different coordinates.

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