I create a module in which I have two images whenever I touch one image, it must follow the finger or mouse (in the emulator) when dragging and if it happens on a different image, then they change their positions, where the first first touch image (ACTION_DOWN). I wrote the following code in which the views move, but when I drag the first image, the second also drags. Next, I would like to have an idea of ββhow to change positions.
.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/vg" > <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/img1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
activity file
public class MainActivity extends Activity { private View selected_item = null; private int offset_x = 0; private int offset_y = 0; Canvas can; Paint paint; ImageView img; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewGroup vg = (ViewGroup)findViewById(R.id.vg); vg.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getActionMasked()) { case MotionEvent.ACTION_MOVE: if(selected_item == img) { int x = (int)event.getX() - offset_x; int y = (int)event.getY() - offset_y; int w = getWindowManager().getDefaultDisplay().getWidth() - 100; int h = getWindowManager().getDefaultDisplay().getHeight() - 100; if(x > w) x = w; if(y > h) y = h; LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( new ViewGroup.MarginLayoutParams( 100, 100)); lp.setMargins(x, y, 0, 0); selected_item.setLayoutParams(lp); } break; default: break; } return true; } }); img = (ImageView)findViewById(R.id.img);
source share