Wednesday, May 21, 2014

move image with finger touch inside layout in android source code

 A touch Listener occurs when a user places one or more fingers on the touch screen, and your application interprets that pattern of touches as a particular gesture. There are correspondingly two phases to gesture detection
  1. Gathering data about touch events.
  2. Interpreting the data to see if it meets the criteria for any of the gestures your app supports. 

Capturing touch events for a single view

As an alternative to onTouchEvent(), you can attach an View.OnTouchListener object to any View object using the setOnTouchListener() method. This makes it possible to to listen for touch events without subclassing an existing View.

Below example will give detailed idea for moving object within layout  using finger touch.

example.xml

 <RelativeLayout
            android:id="@+id/relativelayout"
            android:layout_width="200dp"
            android:layout_height="120dp"
            android:background="@drawable/field" >

            <ImageView
                android:id="@+id/imageview1"
                android:layout_width="30dp"
                android:layout_height="50dp"
                android:layout_centerVertical="true"
                android:src="@drawable/cricket_ball9"
                android:visibility="gone" />
        </RelativeLayout>




In activity

relativelayout.setOnTouchListener(new OnTouchListener() {


            @Override
            public boolean onTouch(View v, MotionEvent event) {
                imageview1.setVisibility(View.VISIBLE);

 imageview1.bringToFront();
                    int y = (int)event.getY();
                    int x = (int)event.getX();
                   
                    imageview1.getLayoutParams().height = 20;
                    imageview1.getLayoutParams().width = 20;
                   
                    imageview1.layout(x, y, x+48, y+48);
                                    }

        });