Androidで複数のビューをドラッグする際に問題が発生します。Canvasを使用して作成された2つの円があります。問題は、1つの円しかドラッグできず、もう1つの円をドラッグできないことです。最初の円が画面全体を覆っているようですが、2番目の円をドラッグしようとすると、まだ1番目の円が動いています。
これが私のコードです。
MainActivity.java
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}}
DragSource.java
public class DragSource extends View {
private Paint viewPaint;
private float startX;
private float startY;
private float touchOffsetX;
private float touchOffsetY;
private float x = 30;
private float y = 30;
private static final float RADIUS = 30;
//needed for finding drop target:
//the constructor:
public DragSource(Context context, AttributeSet attrs) {
super(context, attrs);
viewPaint = new Paint();
viewPaint.setColor(Color.RED);
viewPaint.setAntiAlias(true);
}
public boolean onTouchEvent(MotionEvent mEvent) {
int eventAction = mEvent.getAction();
switch(eventAction)
{
case MotionEvent.ACTION_DOWN:
startX = x;
startY = y;
touchOffsetX = mEvent.getX();
touchOffsetY = mEvent.getY();
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
x = startX + mEvent.getX() - touchOffsetX;
y = startY + mEvent.getY() - touchOffsetY;
break;
}
return true;
}
public void draw(Canvas c) {
int w = c.getWidth();
int h = c.getHeight();
c.drawCircle(x, y, RADIUS, viewPaint);
this.invalidate();
}}
私のactivity_main.xml
<RelativeLayout 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" ><com.example.trialsdrag.DragSource
android:layout_width="wrap_content"
android:layout_height="wrap_content"/><com.example.trialsdrag.DragSource
android:layout_width="wrap_content"
android:layout_height="wrap_content"/></RelativeLayout>