Monday, 25 November 2013

Different ways to handle Click Events in Android

Android: OnClickListener Ways

Overview:

            Android provides Delegate Event Model to handle the click events in different ways.  An Android View in an App will fire an event in response to user or code interaction. The application will not respond to the event unless it is listening for it. To detect the event a class that implements a listener is instantiated and assigned to the View.

          

                There are pros and cons for each method and experienced developers will advocate a particular method over others. But not one of the methods can be regarded as the must do way. Developers need to be familiar with the different ways to code event handlers, they they will come across the different methods in tutorials, samples and online snippets.

             In Event Delegation Model when a View fires an event an Application will not respond to it unless it is listening for it. To detect the event a class that implements a listener is instantiated and assigned to the View. 

       Take for example the onClick event, the most widely used event in Android Apps. Nearly every View that can be added to an App screen will fire the event when the user stabs it with their finger (on touch screens) or presses the trackpad/trackball when the View has focus. This event is listened to by a class implementing the OnClickListener interface. 

The class instance is then assigned to the required View using the View's setOnClickListener method. 

There are different ways of handling the Click event in android.

  1. Member Class
  2. Interface Type
  3. Anonymous Inner Class (Inline method)
  4. Implementation in Activity
  5. Attribute in View Layout for OnClick Events

Below are the implementation ways:

           1. Member Class

         A class called HandleClick implementing OnClickListener is declared as a member of the Activity (MainActivity). This is useful when several listeners require similar processing than can be handled by a single class.

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //attach an instance of HandleClick to the Button
        findViewById(R.id.button1).setOnClickListener(new HandleClick());
    }    
    private class HandleClick implements OnClickListener{
        public void onClick(View arg0) {
     Button btn = (Button)arg0; //cast view to a button
     // get a reference to the TextView
     TextView tv = (TextView) findViewById(R.id.textview1);
     // update the TextView text
     tv.setText("You have pressed " + btn.getText());
 }
    }
}

    2. Interface Type 
            
              In Java an Interface can be used as a type, a variable is declared as an OnClickListener and assigned using new OnClickListener(){...}, behind the scenes Java is creating an object (an Anonymous Class) that implements OnClickListener. This has similar benefits to the first method.

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //use the handleClick variable to attach the event listener
        findViewById(R.id.button1).setOnClickListener(handleClick);
    }    
    private OnClickListener handleClick = new OnClickListener(){
        public void onClick(View arg0) {
     Button btn = (Button)arg0;
     TextView tv = (TextView) findViewById(R.id.textview1);
     tv.setText("You have pressed " + btn.getText());
 }
    };
}

  3. Anonymous Inner Class (Inline method)

           Declaring the OnClickListener within the call to the setOnClickListener method is common. This method is useful when each listener does not have functionality that could be shared with other listeners. Some novice developers find this type of code difficult to understand. This method is very quick but does leave a bit of a mess. I Would only recommend using this for small blocks of code.Again behind the scenes for new OnClickListener(){...} . Java is creating an object that implements the interface.

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(new OnClickListener(){
            public void onClick(View arg0) {
      Button btn = (Button)arg0;
      TextView tv = (TextView) findViewById(R.id.textview1);
      tv.setText("You have pressed " + btn.getText());
         }
        });
    }     
}


4. Implementation in Activity

        The Activity itself can implement the OnClickListener. Since the Activity object (MainActivity) already exists this saves a small amount of memory by not requiring another object to host the onClickmethod. It does make public a method that is unlikely to be used elsewhere. Implementing multiple events will make the declaration of main long.

public class MainActivity extends Activity implements OnClickListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(this);
    }    
    public void onClick(View arg0) {
 Button btn = (Button)arg0;
 TextView tv = (TextView) findViewById(R.id.textview1);
 tv.setText("You have pressed " + btn.getText());
    }
}


5. Attribute in View Layout for OnClick Events

            In Android 1.6 and later (API level 4 and upwards) the name of a method defined in the Activity can be assigned to the android:onClick attribute in a layout file. This can save writing a lot of boilerplate code.

public class MainActivity extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }    
    public void HandleClick(View arg0) {
 Button btn = (Button)arg0;
        TextView tv = (TextView) findViewById(R.id.textview1);
 tv.setText("You have pressed " + btn.getText());
    }
}


In the layout file the Button would be declared with the android:onClick attribute.

<Button android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1"
        android:onClick="HandleClick"/>


    The first four methods of handling events can be used with other event types (onLongClick, onKey, onTouch, onCreateContextMenu, onFocusChange). The fifth method only applies to the onClick event. The layout file below declares an additional two buttons and using the android:onClick attribute no additional code is required than that defined above, i.e. no additional findViewById and setOnClickListener for each button is required.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  <TextView android:id="@+id/textview1"
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="Click a button."
            android:textSize="20dp"/>
  <LinearLayout android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
    <Button android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1"
            android:onClick="HandleClick"/>             
    <Button android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 2"
            android:onClick="HandleClick"/>
    <Button android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 3"
            android:onClick="HandleClick"/>
  </LinearLayout>      
</LinearLayout>


Conclusion

Deciding which technique to use to wire up a listener will depend on the functionality required, how much code is reusable across Views and how easy the code would be to understand by future maintainers. Ideally the code should be sufficient and easy to view.

    One method not shown here is similar to the first method. In the first method it would be possible to save the listener class in a different class file as a public class. Then instances of that public class could be used by other Activities, passing the Activity's context in via the constructor. However, Activities should try and stay self contained in case they are killed by Android. Sharing listeners across Activities is against the ideals of the Android platform and could lead to unnecessary complexity passing references between the public classes.

Monday, 18 November 2013

Drag and Drop Feature in Android 3.0

Overview


QuickView (Highlighting Features)
  • Allow users to move data within your Activity layout using graphical gestures.
  • Supports operations besides data movement.
  • Only works within a single application.
  • Requires API 11.
            A drag and drop operation starts when the user makes some gesture that you recognize as a signal to start dragging data. In response, your application tells the system that the drag is starting. The system calls back to your application to get a representation of the data being dragged. As the user's finger moves this representation (a "drag shadow") over the current layout, the system sends drag events to the drag event listener objects and drag event callback methods associated with the View objects in the layout. Once the user releases the drag shadow, the system ends the drag operation.
You create a drag event listener object ("listeners") from a class that implements View.OnDragListener. You set the drag event listener object for a View with the View object'ssetOnDragListener() method. Each View object also has aonDragEvent() callback method.
When you start a drag, you include both the data you are moving and metadata describing this data as part of the call to the system. During the drag, the system sends drag events to the drag event listeners or callback methods of each View in the layout. The listeners or callback methods can use the metadata to decide if they want to accept the data when it is dropped.


The Drag/Drop process


There are basically four steps or states in the drag and drop process:

Started
      In response to the user's gesture to begin a drag, your application calls startDrag() to tell the system to start a drag. The arguments startDrag() provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow.The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device.

        Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the drag event listeners for all the View objects in the current layout. To continue to receive drag events, including a possible drop event, a drag event listener must return true. This registers the listener with the system. Only registered listeners continue to receive drag events. At this point, listeners can also change the appearance of their View object to show that the listener can accept a drop event.

Continuing
           The user continues the drag. As the drag shadow intersects the bounding box of a View object, the system sends one or more drag events to the View object's drag event listener (if it is registered to receive events). The listener may choose to alter its View object's appearance in response to the event. For example, if the event indicates that the drag shadow has entered the bounding box of the View (action type ACTION_DRAG_ENTERED), the listener can react by highlighting its View.



Dropped
            The user releases the drag shadow within the bounding box of a View that can accept the data. The system sends the View object's listener a drag event with action type ACTION_DROP. The drag event contains the data that was passed to the system in the call to startDrag() that started the operation. The listener is expected to return boolean true to the system if code for accepting the drop succeeds.


Note: This step only occurs if the user drops the drag shadow within the bounding box of a View whose listener is registered to receive drag events. If the user releases the drag shadow in any other situation, noACTION_DROP drag event is sent.

Ended
          After the user releases the drag shadow, and after the system sends out (if necessary) a drag event with action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDEDto indicate that the drag operation is over. This is done regardless of where the user released the drag shadow. The event is sent to every listener that is registered to receive drag events, even if the listener received the ACTION_DROP event.

Technical Points:
          While the view is getting dragged on screen, system generates DragEvents which can be intercepted by application by setting View.setOnDragListener().


          OnDragListener interface has callback method public boolean onDrag(View view, DragEvent dragEvent) which will get called whenever any view is dragged or dropped.The DragEvent parameter provides getAction() which tells the application which type of action has occurred.


Following types of action can be identified.

DragEvent.ACTION_DRAG_STARTED – Drag event has started.
DragEvent.ACTION_DRAG_ENTERED – Drag has brought the drop shadow in view bounds.
DragEvent.ACTION_DRAG_EXITED – Drag has taken the drop shadow out of view bounds.
DragEvent.ACTION_DRAG_LOCATION – Drag is happening and drop shadow is inside view bounds.
DragEvent.ACTION_DROP – Drop has happened inside view bounds.
DragEvent.ACTION_DRAG_ENDED – Drop has happened outside view bounds.

Create and Design the App


Create a new Android project in Eclipse. Enter the application settings of your choice, being sure to create a blank Activity and layout for it.First of all create a layout file for the activity as below:

activity_drag_drop.xml
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="wrap_content"  
   android:orientation="vertical"  
   android:padding="10dp"  
   android:paddingLeft="50dp"  
   android:paddingRight="50dp" >  
   <TextView  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:gravity="center"  
     android:paddingBottom="10dp"  
     android:text="Place these foods in your order of preference." />  
   <TextView  
     android:id="@+id/option_1"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_margin="5dp"  
     android:background="@drawable/option"  
     android:gravity="center"  
     android:text="Apple"  
     android:textStyle="bold" />  
   <TextView  
     android:id="@+id/option_2"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_margin="5dp"  
     android:background="@drawable/option"  
     android:gravity="center"  
     android:text="Cake"  
     android:textStyle="bold" />  
   <TextView  
     android:id="@+id/option_3"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_margin="5dp"  
     android:background="@drawable/option"  
     android:gravity="center"  
     android:text="Orange"  
     android:textStyle="bold" />  
   <TextView  
     android:id="@+id/choice_1"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_margin="5dp"  
     android:background="@drawable/choice"  
     android:gravity="center"  
     android:text="Most Favourite" />  
   <TextView  
     android:id="@+id/choice_2"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_margin="5dp"  
     android:background="@drawable/choice"  
     android:gravity="center"  
     android:text="---" />  
   <TextView  
     android:id="@+id/choice_3"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_margin="5dp"  
     android:background="@drawable/choice"  
     android:gravity="center"  
     android:text="Not Favourite" />  
 </LinearLayout>  

Below are the xml's of choice & options which are used to set in TextView. Put it in “res/drawables” folder

option.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <shape xmlns:android="http://schemas.android.com/apk/res/android"  
   android:dither="true" >  
   <solid android:color="#ff00ccff" />  
   <corners android:radius="2dp" />  
   <stroke  
     android:width="2dp"  
     android:color="#ff0099cc" />  
   <padding  
     android:bottom="5dp"  
     android:left="10dp"  
     android:right="10dp"  
     android:top="5dp" />  
 </shape>  

choice.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <shape xmlns:android="http://schemas.android.com/apk/res/android"  
 android:dither="true" >  
    <solid android:color="#ffffff99" />  
    <corners android:radius="2dp" />  
    <stroke  
      android:dashGap="4dp"  
      android:dashWidth="2dp"  
      android:width="2dp"  
      android:color="#ffffff00" />  
   <padding  
     android:bottom="5dp"  
     android:left="5dp"  
     android:right="5dp"  
     android:top="5dp" />  
 </shape>  

Here is the activity code DragDropActivity.java
 import android.os.Bundle;  
 import android.app.Activity;  
 import android.content.ClipData;  
 import android.graphics.Typeface;  
 import android.view.DragEvent;  
 import android.view.MotionEvent;  
 import android.view.View;  
 import android.view.View.DragShadowBuilder;  
 import android.view.View.OnDragListener;  
 import android.view.View.OnTouchListener;  
 import android.widget.TextView;  
 public class DragDropActivity extends Activity {  
  //text views being dragged and dropped onto  
  private TextView option1, option2, option3, choice1, choice2, choice3;  
  @Override  
  protected void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.activity_drag_drop);  
  //get both sets of text views  
  //views to drag  
  option1 = (TextView)findViewById(R.id.option_1);  
  option2 = (TextView)findViewById(R.id.option_2);  
  option3 = (TextView)findViewById(R.id.option_3);  
  //views to drop onto  
  choice1 = (TextView)findViewById(R.id.choice_1);  
  choice2 = (TextView)findViewById(R.id.choice_2);  
  choice3 = (TextView)findViewById(R.id.choice_3);  
  //set touch listeners  
  option1.setOnTouchListener(new ChoiceTouchListener());  
  option2.setOnTouchListener(new ChoiceTouchListener());  
  option3.setOnTouchListener(new ChoiceTouchListener());  
  //set drag listeners  
  choice1.setOnDragListener(new ChoiceDragListener());  
  choice2.setOnDragListener(new ChoiceDragListener());  
  choice3.setOnDragListener(new ChoiceDragListener());  
  }  
  /**  
  * ChoiceTouchListener will handle touch events on draggable views  
  *  
  */  
  private final class ChoiceTouchListener implements OnTouchListener {  
  public boolean onTouch(View view, MotionEvent motionEvent) {  
   if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {  
   /*  
    * Drag details: we only need default behavior  
    * - clip data could be set to pass data as part of drag  
    * - shadow can be tailored  
    */  
   ClipData data = ClipData.newPlainText("", "");  
   DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);  
   //start dragging the item touched  
   view.startDrag(data, shadowBuilder, view, 0);  
   return true;  
   } else {  
   return false;  
   }  
  }  
  }   
  /**  
  * DragListener will handle dragged views being dropped on the drop area  
  * - only the drop action will have processing added to it as we are not  
  * - amending the default behavior for other parts of the drag process  
  *  
  */  
  private class ChoiceDragListener implements OnDragListener {  
  @Override  
  public boolean onDrag(View v, DragEvent event) {  
   switch (event.getAction()) {  
   case DragEvent.ACTION_DRAG_STARTED:  
   //no action necessary  
   break;  
   case DragEvent.ACTION_DRAG_ENTERED:  
   //no action necessary  
   break;  
   case DragEvent.ACTION_DRAG_EXITED:      
   //no action necessary  
   break;  
   case DragEvent.ACTION_DROP:  
   //handle the dragged view being dropped over a drop view  
   View view = (View) event.getLocalState();  
   //stop displaying the view where it was before it was dragged  
   view.setVisibility(View.INVISIBLE);  
   //view dragged item is being dropped on  
   TextView dropTarget = (TextView) v;  
   //view being dragged and dropped  
   TextView dropped = (TextView) view;  
   //update the text in the target view to reflect the data being dropped  
   dropTarget.setText(dropped.getText());  
   //make it bold to highlight the fact that an item has been dropped  
   dropTarget.setTypeface(Typeface.DEFAULT_BOLD);  
   //if an item has already been dropped here, there will be a tag  
   Object tag = dropTarget.getTag();  
   //if there is already an item here, set it back visible in its original place  
   if(tag!=null)  
   {  
    //the tag is the view id already dropped here  
    int existingID = (Integer)tag;  
    //set the original view visible again  
    findViewById(existingID).setVisibility(View.VISIBLE);  
   }  
   //set the tag in the target view being dropped on - to the ID of the view being dropped  
   dropTarget.setTag(dropped.getId());  
   break;  
   case DragEvent.ACTION_DRAG_ENDED:  
   //no action necessary  
   break;  
   default:  
   break;  
   }  
   return true;  
  }  
  }   
 }  


Output:






Thanks.
Enjoy. 

Sunday, 17 November 2013

Android FaceDetection Feature in Camera

Overview:

The difference between the Face Detection & Face Recognization :

1) Face detection :- Find the face in the photo
2) Face recognition :- Identify the face in camera

  • FaceDetection is support by the android from the API level 1.

             The android.media.FaceDetector class, configured with the size of the images to be analysed and the maximum number of faces that can be detected.

             These parameters cannot be changed once the object is constructed. Note that the width of the image must be even.

           In this sample application we will detect the faces in the given photograph. The application will detect the number of faces in the image and draws a rectangle around each face in the image. So here we will load an image into our project and detect if it has faces or not. 

        In real life you would probably want to capture the image using the camera, or choose the image from a Gallery to detect face in it.


Below is the Code implementation of the Face Detection in android: 

1) Create a class FaceDetectionActivity.java

In your onCreate() method write setContentView(new MyView(this)); after call to super.
  @Override  
   public void onCreate(Bundle savedInstanceState)  
   {  
     super.onCreate(savedInstanceState);  
     setContentView(new MyView(this));  
   }  

  So our next step is to create MyView Class.
  public MyView(Context context)  
  {  
    super(context);  
    BitmapFactory.Options bitmapFatoryOptions=new BitmapFactory.Options();  
    bitmapFatoryOptions.inPreferredConfig=Bitmap.Config.RGB_565;  
    myBitmap=BitmapFactory.decodeResource(getResources(),  
 R.drawable.faceswapping,bitmapFatoryOptions);  
    width=myBitmap.getWidth();  
    height=myBitmap.getHeight();  
   detectedFaces=new FaceDetector.Face[NUMBER_OF_FACES];  
   faceDetector=new FaceDetector(width,height,NUMBER_OF_FACES);  
   NUMBER_OF_FACE_DETECTED=faceDetector.findFaces(myBitmap, detectedFaces);  
  }  
  • For FaceDetection we need to convert in bitmap format that too in RGB_565.
  • Now get the image from the drawable folder. Get the width and height of image.
  • Now the reason I feel this API the simplest is coming now.
  • You need to pass the number of faces you want to detect.It will return the array of Face type.Last three lines is having logic for that.So you must declare an array with the size of number of faces you want to detect.

Now when the face gets detected we will draw a red rectangle on it.For that we need to write few lines in our onDraw() method.
   @Override  
   protected void onDraw(Canvas canvas)  
   {  
     canvas.drawBitmap(myBitmap, 0,0, null);  
     Paint myPaint = new Paint();  
     myPaint.setColor(Color.GREEN);  
     myPaint.setStyle(Paint.Style.STROKE);  
     myPaint.setStrokeWidth(3);  
     for(int count=0;count<NUMBER_OF_FACE_DETECTED;count++)    {  
         Face face=detectedFaces[count];  
         PointF midPoint=new PointF();  
         face.getMidPoint(midPoint);  
         eyeDistance=face.eyesDistance();  
         canvas.drawRect(midPoint.x-eyeDistance, midPoint.y-eyeDistance,         midPoint.x+eyeDistance, midPoint.y+eyeDistance, myPaint);  
     }  
    }  

drawRect is taking five parameter left x,y and top x,y coordinate.From that given pint it will start drawing rectangle.We need to pass paint object also.

Here is the Full source of FacedetectionActivity.java.
 public class FaceDetectionActivity extends Activity {  
 /** Called when the activity is first created. */  
  @Override  
  public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(new MyView(this));  
  }  
 /**  
 * Class which render the layout of the image and detect the face from the image.  
 */  
 private class MyView extends View {  
     private Bitmap m_Bitmap;  
     private int m_width, m_height;  
     private FaceDetector.Face[] m_detectedFaces;  
     private int NUMBER_OF_FACES = 6;  
     private FaceDetector m_faceDetector;  
     private int NUMBER_OF_FACE_DETECTED;  
     private float m_eyeDistance;  
  public MyView(Context p_context) {  
     super(p_context);  
     BitmapFactory.Options m_bitmapFatoryOptions = new BitmapFactory.Options();  
     m_bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;  
     m_Bitmap = BitmapFactory.decodeResource(getResources(),  
       R.drawable.faceswapping, m_bitmapFatoryOptions);  
     m_width = m_Bitmap.getWidth();  
     m_height = m_Bitmap.getHeight();  
     m_detectedFaces = new FaceDetector.Face[NUMBER_OF_FACES];  
     m_faceDetector = new FaceDetector(m_width, m_height, NUMBER_OF_FACES);  
     NUMBER_OF_FACE_DETECTED = m_faceDetector.findFaces(m_Bitmap,m_detectedFaces);  
  }  
   @Override  
   protected void onDraw(Canvas p_canvas)   
   {  
      p_canvas.drawBitmap(m_Bitmap, 0, 0, null);  
      Paint m_Paint = new Paint();  
      m_Paint.setColor(Color.GREEN);  
      m_Paint.setStyle(Paint.Style.STROKE);  
      m_Paint.setStrokeWidth(3);  
    for (int m_count = 0; m_count < NUMBER_OF_FACE_DETECTED; m_count++)   
    {  
      Face m_face = m_detectedFaces[m_count];  
      PointF m_midPoint = new PointF();  
      m_face.getMidPoint(m_midPoint);  
      m_eyeDistance = m_face.eyesDistance();  
      p_canvas.drawRect(m_midPoint.x - m_eyeDistance, m_midPoint.y- m_eyeDistance, m_midPoint.x + m_eyeDistance, m_midPoint.y+ m_eyeDistance, m_Paint);  
    }  
   }  
  }  
 }  

Output:





For more detailed implementation check out HERE

Thanks.
Enjoy.

Monday, 11 November 2013

Simple Drag & Drop Views on Screen in Android

Hello Friends, Today i am going to share with you a simple drag and drop or give the motion to any object and move it around the screen onTouch event within the screen boundries.


First of all create android project in your eclipse and create a class and layout file as below:

MainActivity.java
 public class MainActivity extends Activity  
 {  
  private ImageView m_ivImage, m_ivImage1;  
  private int m_counter = 0;  
  float m_lastTouchX, m_lastTouchY, m_posX, m_posY, m_prevX, m_prevY, m_imgXB, m_imgYB, m_imgXC, m_imgYC, m_dx, m_dy;  
  private LinearLayout m_llTop;  
  private AbsoluteLayout m_alTop;  
  private Button m_btnAddView, m_btnRemove;  
  private Context m_context;  
  @Override  
  public void onCreate(Bundle savedInstanceState)  
  {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.main_layout);  
  m_context = this;  
  m_prevX = 0;  
  m_prevY = 0;  
  m_imgXB = 50;  
  m_imgYB = 100;  
  m_imgXC = 150;  
  m_imgYC = 100;  
  m_ivImage = (ImageView) findViewById(R.id.ivImage);  
  m_ivImage1 = (ImageView) findViewById(R.id.ivImage1);  
  m_llTop = (LinearLayout) findViewById(R.id.llTop);  
  m_alTop = (AbsoluteLayout) findViewById(R.id.alTop);  
  m_btnAddView = (Button) findViewById(R.id.btnAdd);  
  m_btnRemove = (Button) findViewById(R.id.btnRemove);  
  m_ivImage.setOnTouchListener(m_onTouchListener);  
  m_ivImage1.setOnTouchListener(m_onTouchListener);  
  m_btnAddView.setOnClickListener(m_onClickListener);  
  m_btnRemove.setOnClickListener(m_onClickListener);  
  }  
  OnClickListener m_onClickListener = new OnClickListener(){  
  @Override  
  public void onClick(View p_v)  
  {  
   switch (p_v.getId())  
   {  
    case R.id.btnAdd:  
    addView();  
    break;  
    case R.id.btnRemove:  
    removeView();  
    break;  
    default:  
    break;  
   }  
  }  
  };  
  OnTouchListener m_onTouchListener = new OnTouchListener(){  
  @Override  
  public boolean onTouch(View p_v, MotionEvent p_event)  
  {  
   switch (p_event.getAction())  
   {  
    case MotionEvent.ACTION_DOWN:  
    {  
    m_lastTouchX = p_event.getX();  
    m_lastTouchY = p_event.getY();  
    break;  
    }  
    case MotionEvent.ACTION_UP:  
    {  
    break;  
    }  
    case MotionEvent.ACTION_MOVE:  
    {  
    m_dx = p_event.getX() - m_lastTouchX;  
    m_dy = p_event.getY() - m_lastTouchY;  
    m_posX = m_prevX + m_dx;  
    m_posY = m_prevY + m_dy;  
    if (m_posX > 0 && m_posY > 0 && (m_posX + p_v.getWidth()) < m_alTop.getWidth() && (m_posY + p_v.getHeight()) < m_alTop.getHeight())  
    {  
     p_v.setLayoutParams(new AbsoluteLayout.LayoutParams(p_v.getMeasuredWidth(), p_v.getMeasuredHeight(), (int) m_posX, (int) m_posY));  
     m_prevX = m_posX;  
     m_prevY = m_posY;  
    }  
    break;  
    }  
   }  
   return true;  
  }  
  };  
  /**  
  * Add view dynamically for drag and drop  
  */  
  private void addView()  
  {  
  ImageView m_img = new ImageView(m_context);  
  TextView m_tv=new TextView(m_context);  
  if (m_counter < 5)  
  {  
   if (m_counter % 2 == 0)  
   {  
   m_img.setBackgroundResource(R.drawable.bol_green);  
   m_tv.setText("Hello! Drag Me! ");  
   m_alTop.addView(m_tv, new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, ((int) m_imgXB), ((int) m_imgYB)));  
   m_alTop.addView(m_img, new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, ((int) m_imgXB), ((int) m_imgYB)));  
   }  
   else  
   {  
   m_img.setBackgroundResource(R.drawable.bol_paars);  
   m_alTop.addView(m_img, new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, ((int) m_imgXC), ((int) m_imgYC)));  
   }  
   m_counter++;  
   if (m_counter == 5)  
   m_btnAddView.setEnabled(false);  
  }  
  m_img.setOnTouchListener(m_onTouchListener);  
  m_tv.setOnTouchListener(m_onTouchListener);  
  }  
  public void removeView()  
  {  
  m_counter = 0;  
  m_alTop.removeAllViews();  
  m_alTop.invalidate();  
  m_btnAddView.setEnabled(true);  
  }  
 }  
main_layout.xml
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:id="@+id/llTop"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent"  
   android:orientation="vertical" >  
   <AbsoluteLayout  
     android:id="@+id/alTop"  
     android:layout_width="fill_parent"  
     android:layout_height="0dp"  
     android:layout_margin="10dp"  
     android:layout_weight=".70"  
      >  
     <ImageView  
       android:id="@+id/ivImage"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_marginTop="10dp"  
       android:src="@drawable/ic_menu_share"  
       android:visibility="gone" />  
     <ImageView  
       android:id="@+id/ivImage1"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_marginLeft="10dp"  
       android:layout_marginTop="10dp"  
       android:layout_x="193dp"  
       android:layout_y="29dp"  
       android:src="@drawable/ic_launcher" />  
   </AbsoluteLayout>  
   <LinearLayout  
     android:layout_width="wrap_content"  
     android:layout_height="0dp"  
     android:layout_gravity="center"  
     android:layout_weight=".30" >  
     <Button  
       android:id="@+id/btnAdd"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_marginTop="10dp"  
       android:text="Add View" />  
     <Button  
       android:id="@+id/btnRemove"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_marginTop="10dp"  
       android:text="Remove View"  
       android:visibility="visible" />  
   </LinearLayout>  
 </LinearLayout>  

Here is the boundary file xml code which shows the border of the layout in which object moves.

 <?xml version="1.0" encoding="utf-8"?>  
 <selector  
   xmlns:android="http://schemas.android.com/apk/res/android">  
   <item>  
  <shape>    
      <stroke  
         android:width="1dp"  
         android:color="#000000"/>     
     <corners          
         android:topLeftRadius="8dp"  
         android:topRightRadius="8dp"  
         android:bottomLeftRadius="8dp"  
         android:bottomRightRadius="8dp"/>   
   <padding  
        android:left="0dp"  
        android:top="0dp"  
        android:right="0dp"  
        android:bottom="0dp"/>  
     <gradient  
      android:angle="270"   
      android:endColor="#FFFFFF"  
      android:startColor="#FFFFFF"  
      android:type="linear"  
      android:centerColor="#FFFFFF"/>  
     </shape>  
    </item>  
 </selector>  

Screenshot