1

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>
4

1 に答える 1

1

何が起こっているのかというと、ビューのサイズは実際には画面全体のサイズであり、では、ビューのonTouchEvent描画を変更する(円を移動する)だけです。

で行う必要があるのは、のDragSourceを設定android:layout_heightし、次を使用してレイアウトマージンを動的に変更することです。android:layout_widthmain_activity.xmlonTouchEvent

RelativeLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.setMargins(x+params.leftMargin, y+params.topMargin, 0, 0);
setLayoutParams(params);
于 2012-10-15T09:30:50.997 に答える