Hello Friends Here is Code for image drag and move
move image view in android anywhere in device screen for that here some code for that move image view using single touch,
drag image view in android
java Code
import android.app.Activity;
import android.os.Bundle;
import
android.view.MotionEvent;
import android.view.View;
import
android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
public class MainActivity extends Activity {
int windowwidth;
int windowheight;
private LayoutParams layoutParams;
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
windowwidth =
getWindowManager().getDefaultDisplay().getWidth();
windowheight =
getWindowManager().getDefaultDisplay().getHeight();
final ImageView img =
(ImageView) findViewById(R.id.imageView1);
img.setOnTouchListener(new
View.OnTouchListener() {
@Override
public boolean onTouch(View v,
MotionEvent event) {
LayoutParams
layoutParams = (LayoutParams) img
.getLayoutParams();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
int x_cord = (int) event.getRawX();
int y_cord = (int) event.getRawY();
if (x_cord > windowwidth) {
x_cord
= windowwidth;
}
if (y_cord > windowheight) {
y_cord
= windowheight;
}
layoutParams.leftMargin = x_cord - 25;
layoutParams.topMargin = y_cord - 75;
img.setLayoutParams(layoutParams);
break;
default:
break;
}
return true;
}
});
}
}
========================================================
layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ball" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/space_icon" />
</LinearLayout>
thanks Enjoy...!
thanks you
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeletelayoutParams.leftMargin = x_cord - 25;
ReplyDeletelayoutParams.topMargin
leftMargin and topmargin are not working in my codes..
Thanks a lot.
ReplyDeleteleftMargin and topmargin are not recognized in my code
ReplyDeleteFor Left Margin and Top Margin use this Import:
ReplyDeleteimport android.widget.LinearLayout.LayoutParams;
OR
import android.widget.RelativeLayout.LayoutParams;
OR
Parent layout of your choice
With dragging imageView1 other images are also moving to right.why? and how to stop that
ReplyDeleteset object between Screen without collapse image
ReplyDelete