Showing posts with label drag and drop. Show all posts
Showing posts with label drag and drop. Show all posts

Wednesday, August 21, 2013

Drag and Drop Example

Drag and Drop is useful in canvas or drawing application.Here is full description,just follow it.


  • Modify the code in activity_main.xml file.

activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Drag Me" >
    </Button>

</FrameLayout>


  • Add below code in MainActivity.java file.

MainActivity.java



public class Home extends Activity implements OnTouchListener {


private final static int START_DRAGGING = 0;
private final static int STOP_DRAGGING = 1;

private Button btn;
private FrameLayout layout;
private int status;
private LayoutParams params;

private ImageView image;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

layout = (FrameLayout) findViewById(R.id.LinearLayout01);
// layout.setOnTouchListener(this);

btn = (Button) findViewById(R.id.btn);
btn.setDrawingCacheEnabled(true);
btn.setOnTouchListener(this);

params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);

}

@Override
public boolean onTouch(View view, MotionEvent me) 
{
if (me.getAction() == MotionEvent.ACTION_DOWN) {
status = START_DRAGGING;
image = new ImageView(this);
image.setImageBitmap(btn.getDrawingCache());
layout.addView(image, params);
}
if (me.getAction() == MotionEvent.ACTION_UP) {
status = STOP_DRAGGING;
Log.i("Drag", "Stopped Dragging");
} else if (me.getAction() == MotionEvent.ACTION_MOVE) {
if (status == START_DRAGGING) {
System.out.println("Dragging");
image.setPadding((int) me.getRawX(), (int) me.getRawY(), 0, 0);
image.invalidate();
}
}
return false;
}
}

  • Done ! Now Run the Project.Try to drag button.