その画像を親ビューでのみドラッグしたい。ユーザーがビューの外にドラッグしようとすると、元の位置に戻ります。基本的に私はアンドロイドのロック解除タイプの機能を実装しています。私を助けてください。それは私のメインクラスです。
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.myimage1).setOnTouchListener(new MyTouchListener());
findViewById(R.id.topleft).setOnDragListener(new MyDragListener());
}
private final class MyTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
class MyDragListener implements OnDragListener {
Drawable enterShape = getResources().getDrawable(R.drawable.shape_droptarget);
Drawable normalShape = getResources().getDrawable(R.drawable.shape);
@Override
public boolean onDrag(View v, DragEvent event) {
//int action = event.getAction();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// Do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
v.setBackgroundResource(R.drawable.shape_droptarget);
break;
case DragEvent.ACTION_DRAG_EXITED:
v.setBackgroundResource(R.drawable.shape);
setFinishOnTouchOutside(true);
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
View view = (View) event.getLocalState();
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
LinearLayout container = (LinearLayout) v;
container.addView(view);
view.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENDED:
v.setBackgroundResource(R.drawable.shape);
default:
break;
}
return true;
}
}
}
メインxml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/topleft"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:background="@drawable/shape" >
<ImageView
android:id="@+id/myimage1"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
</RelativeLayout>