Friday, June 21, 2013

Detecting Swipe Event In Android

To detect Touch Event and other events like Left to Right sweep and Right to Left sweep, we use  MotionEvent  class.

MotionEvent


MotionEvent object is used to report movement (mouse, pen, finger, trackball) events. Motion events may hold either absolute or relative movements and other data, depending on the type of device.

Motion events describe movements in terms of an action code and a set of axis values. The action code specifies the state change that occurred such as a pointer going down or up. The axis values describe the position and other movement properties.

For example, when the user first touches the screen, the system delivers a touch event to the appropriate View with the action code ACTION_DOWN and a set of axis values that include the X and Y coordinates of the touch and information about the pressure, size and orientation of the contact area.


In the code below I have described with proper Source Code about detecting Swap Events but first we should understand the basics.

onTouchEvent () method ogets called when User performs any touch event on screen

when a User swaps from Left to Right or Right to left

user first touches on the screen ( lets say first x coordinate is x1) holds ,swaps  then leaves the screen  (lets say second x coordinate is x2)

so if x2> x1  it means Left to Right sweep has been performed and
     if x2<x1   it means Right to Left sweep has been performed

Similarly we can track UP to Down and Down to UP swap

if  y2> y1  it means UP to Down sweep has been performed and
if  y2<y1   it means Down to UP sweep has been performed

Example with Source Code


main.xml


TouchEvent



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

        <TextView
            android:layout_marginTop="80dp"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:gravity="center"
            android:textColor="#000099"
            android:textSize="30dp"
            android:text="Detect Swap Event Demo" />
       
   
</LinearLayout>




MainActivity.java


public class MainActivity extends Activity
{
            float x1,x2;
            float y1, y2;
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.main);
            }
          
            //
onTouchEvent () method gets called when User performs any touch event on screen 
           // Method to handle touch event like left to right swap and right to left swap
                        public boolean onTouchEvent(MotionEvent touchevent)
                        {
                                     switch (touchevent.getAction())
                                     {
                                            // when user first touches the screen we get x and y coordinate
                                             case MotionEvent.ACTION_DOWN:
                                             {
                                                 x1 = touchevent.getX();
                                                 y1 = touchevent.getY();
                                                 break;
                                            }
                                             case MotionEvent.ACTION_UP:
                                             {
                                                 x2 = touchevent.getX();
                                                 y2 = touchevent.getY(); 


                                                 / /if left to right
sweep event on screen
                                                 if (x1 < x2)
                                                 {
                                                     Toast.makeText(this, "Left to Right Swap Performed", Toast.LENGTH_LONG).show();
                                                  }
                                               
                                                 // if right to left sweep event on screen

                                                 if (x1 > x2)
                                                 {
                                                     Toast.makeText(this, "Right to Left Swap Performed", Toast.LENGTH_LONG).show();
                                                 }
                                               
                                                 // if UP to Down
sweep event on screen
                                                 if (y1 < y2)
                                                 {
                                                     Toast.makeText(this, "UP to Down Swap Performed", Toast.LENGTH_LONG).show();
                                                 }
                                               
                                                 / /if Down to UP
sweep event on screen
                                                 if (y1 > y2)
                                                 {
                                                     Toast.makeText(this, "Down to UP Swap Performed", Toast.LENGTH_LONG).show();
                                                  }
                                                 break;
                                             }
                                     }
                                     return false;
                        }

  
}





TouchEvent




55 comments:

  1. thanks very simple and good example

    ReplyDelete
  2. Very Good Example Sir But How Do You Do It Using A Image i.e., Sliding a Image and Viewing A Text ??/

    ReplyDelete
  3. Good But How To Swipe With A Image To Top To Display Something ??? Please Help Out !!!

    ReplyDelete
  4. It's simple but sometimes left-right swap and down-up swap both performs, tell me why?

    ReplyDelete
    Replies
    1. If the user doesn't swipe exactly left to right (y1=y2) or up to down (x1=x2) then both events are detected. To solve this compare the difference of the x values with the difference of the y values. A greater difference between the x values means a left to right swipe. In the code add two float variables after the float y1,y2;
      float diffx, diffy;
      Right before the first if statement include the lines
      diffx = x2-x1;
      diffy = y2-y1;
      Within the if statements add as follows:
      if (x1 < x2 && Math.abs(diffy) < Math.abs(diffx))
      if (x2 < x1 && Math.abs(diffy) < Math.abs(diffx))
      if (y1 < y2 && Math.abs(diffx) < Math.abs(diffy))
      if (y2 < y1 && Math.abs(diffy) < Math.abs(diffx))

      Delete
    2. Hi sir how exactly are we going to add the if statements? could you please provide a sample. thank you

      Delete
    3. down to up dosen't work....when i include above code... and left to right n down to up both work on same time...give a solution..thanks in advance

      Delete
  5. Very clear tutorial, I want to ask though.. here we check up and down left and right if we want diagonal we just combine the up and left for example?

    ReplyDelete
  6. Very good example, but if we want to check diagonal? we just combine for example the up and left at the same time?

    ReplyDelete
  7. that's very good example but tost is running which not required at one action also perform downup and updaown in this example.........

    ReplyDelete
  8. Great tutorial with clear explanation.

    ReplyDelete
  9. Simple is best, Thank you.

    ReplyDelete
  10. how can we get on click () including this all...

    ReplyDelete
  11. i want to handle onclick on listitem too,among these all events... how can i do that

    ReplyDelete
  12. Thank you, very simple, very clear.

    ReplyDelete
  13. Thank you, very simple, very clear.

    ReplyDelete
  14. very simple and clear.. thanks alot and keep it up

    ReplyDelete
  15. good example... bt what if we wnt to swipe to another page? how can we do this?

    ReplyDelete
  16. If i want to just swipe horiztonally, how do I accomplish this? I tried to disable "y" but it still allows swipe vertically.

    ReplyDelete
  17. Thanks ! That's great.

    ReplyDelete
  18. How can i enable scrolling Y axis with this code?

    ReplyDelete
  19. Hello,
    if (x1 > x2)
    {
    Toast.makeText(this, "Right to Left Swap Performed", Toast.LENGTH_LONG).show();
    How to change TextView
    }

    ReplyDelete
    Replies
    1. First give id to TextView of Detect Swap Event Demo in main.xml
      and then
      if (x1 > x2)
      {
      Toast.makeText(this, "Right to Left Swap Performed", Toast.LENGTH_LONG).show();
      // to change TextView
      TextView tv = (TextView) findViewById(R.id.textView1);
      tv.setText("It has now Moved to Right");
      }

      Delete
    2. Glad to see fuuastians reply :) (Y)

      Delete
  20. Very Helpful for beginners!!

    ReplyDelete
  21. nice bro!
    its work fine here.

    thank you!

    ReplyDelete
  22. very nice sir,thank you so much!!!

    ReplyDelete
  23. Thanks it help us very much

    ReplyDelete
  24. Thaks A LOT. It REALLY helps me.

    ReplyDelete
  25. thaaaaaanks alooooot
    i searched for this method about one weak but i didnt find any thing
    thank you very much

    ReplyDelete
  26. Really nice,clear explanation got..,Thanks

    ReplyDelete
  27. Really nice,clear explanation,simple code,thanks

    ReplyDelete
  28. Hello, your article is very nice...
    if(x1>x2)
    {
    How to highlight textview part from x1 to x2?
    }

    ReplyDelete
  29. hello .. in above snippet , if i want to highlight that textview contain on which swapping has been performed , so how can i do that?

    ReplyDelete
  30. however you will need them reeling or on one leg. On the off chance that they move back after a phony assault, this may be sufficient to get them cockeyed and afterward you can rearrange bounce advance and apply the scope. broom and dustpan

    ReplyDelete
  31. Read Shayari in Hindi, Best & New Hindi Shayari on Love, Sad, Funny, Friendship, Bewafai, Dard, GoodMorning, GoodNight, Judai, Mehakal, Whatsapp Status in Hindi & English

    Shayari By Categories:-

    Ab Shayari.Guru
    MAHAKAL STATUS
    MOTIVATIONAL QUOTES
    ATTITUDE STATUS
    BEWAFA SHAYARI
    SHARABI SHAYARI

    ReplyDelete
  32. Pls rewrite to Kotlin

    ReplyDelete
  33. Awesome and a great value article. Really nice really good one



    lovely ki shayari

    ReplyDelete
  34. Hello! I love your writing very much! How can we stay in touch with regards to your posts on AOL? I need an expert to solve my issue. Perhaps you're the one! I am looking forward to seeing you. Horoscope Reading Specialist , Husband & Wife Problems Specialist,

    ReplyDelete
  35. I got what you intend, thankyou for putting up.Woh I am thankful to find this website through google. “Food is the most primitive form of comfort. Get Your Love Back In Melbourne, Famous Astrologer In Melbourne Things To Know Before You Buy, |
    The Single Best Strategy To Use For Top Astrologer In Sydney,

    ReplyDelete
  36. ในปัจจุบันที่ทุคนต่างก็มองหาสิ่งที่จะอำนวยความสะดวกให้กับตัวเอง เพราะเทคโนโลยีต่างๆ ที่เข้ามามีส่วนสำคัญในชีวิต โดยเฉพาะในเรื่องของ แทงบอล ซึ่งจะดีกว่าไหม หากท่านได้เดิมพันอยู่ที่บ้าน ผ่านทางโทรศัพท์มือถือ ได้ตลอด 24 ชั่วโมง กับเว็บพนัน UFA888 เป็นเว็บพนันบอลออนไลน์สามารถตอบโจทย์ต่อความต้องการของผู้คน และทำให้ได้รับความสะดวกสบายมากกว่าในหลาย ๆ ด้าน อีกทั้งยังสามารถสร้างรายได้ ได้ดีกว่าการเดิมพันแบบเดิม ๆ โดยเฉพาะที่เว็บของเรา ที่มีอัตราการจ่ายผลกำไรที่มากกว่าตามโต๊ะบอล หรือเว็บอื่น ๆ ถึง 3 เท่าเลยทีเดียว

    ReplyDelete
  37. หากพูดถึงเว็บไซต์ที่เหมาะแก่การเดิมพัน บอลโลก 2022 มากที่สุด ชื่อของเว็บ UFA888 ก็คงจะขึ้นมาเป็นอันดับต้น ๆ อย่างแน่นอน เพราะเว็บแห่งนี้ได้เปิดให้นักพนันได้ร่วมสนุกไปกับการ แทงบอลโลก ได้อย่างเต็มรูปแบบ ที่จะสามารถเลือกคู่แข่งขันสำหรับการเดิมพันได้ครบทุกแมตช์ตลอดฤดูกาล มาพร้อมกับราคาบอลเพียง 4 ตังค์เท่านั้น อีกทั้งยังให้ผู้เล่นได้ลงทุนไปกับเงินเริ่มต้นเพียง 10 บาทเท่านั้น

    ReplyDelete
  38. คาสิโนออนไลน์ระดับพรีเมี่ยม ที่มีสาวสวยมาแจกไพ่ ระบบฝาก-ถอน Auto 10 วินาที ไม่ต้องรอคอย คอนเซปนี้ชื่อว่า Sexy บาคาร่า หรือที่เรียกว่าเย้ายวน พวกเราย้ำบริการให้ผู้เล่นได้เจอกับการแปลกใหม่จากเดิมที่ PGSLOT

    ReplyDelete
  39. I enjoy your writing very much! Do you mind if we communicate with regards to your posts on AOL? I need an expert to solve my issue. Maybe you are the one!
    We are looking forward to seeing you. Astrologer In New York,

    ReplyDelete
  40. UFABET888 สุดยอดผู้ให้บริการเกมเดิมพันออนไลน์ชื่อดังอย่างสล็อตออนไลน์ เว็บเดิมพันออนไลน์ที่เป็นผู้ในทางด้านสำหรับเกม สล็อตออนไลน์ ที่นักลงทุนชาวต่างชาติทั่วโลก เลือกเข้ามาใช้บริการมากที่สุดในเอเชีย นี่เป็นเว็บ สล็อตออนไลน์ที่ดีที่สุดในเอเชีย ที่มีการต้อนรับให้กิจกรรมต่าง ๆ มากมายให้กับนักพนันออนไลน์หน้าใหม่ทุกท่าน ไม่ว่าท่นาจะมีเงินในการลงทุนเพื่อเล่นพนันออนไลน์มากน้อยเพียงใด ท่านก็สามารถเข้ามาเดิมพันได้ง่าย ๆ กับเว็บพนัน UFABET888 โดยที่ไม่ต้องใช้เงินของตัวเองในการลงทุน

    ReplyDelete