拖动时将数据附加到不同的视图

时间:2012-11-02 00:22:29

标签: android

我有多个视图被拖动,每个视图代表一种情感。我们的想法是让每个视图向数据库发送一个条目,该条目根据拖动的视图而变化。

在这里创建视图:

_root = (ViewGroup)findViewById(R.id.root);

_view = new ImageView(this);
_view.setImageResource(R.drawable.smile); 
_view2 = new ImageView(this);
_view2.setImageResource(R.drawable.frown); 



RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(150, 50);
layoutParams.leftMargin = 250;
layoutParams.topMargin = 250;
layoutParams.bottomMargin = -250;
layoutParams.rightMargin = -250;
_view.setLayoutParams(layoutParams);
_view.setOnTouchListener(this);

RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(150, 50);
layoutParams2.leftMargin = 250;
layoutParams2.topMargin = 500;
layoutParams2.bottomMargin = -250;
layoutParams2.rightMargin = -250;
_view2.setLayoutParams(layoutParams2);
_view2.setOnTouchListener(this);
_root.addView(_view);
_root.addView(_view2);

}

此处定义了移动和拖动:

public boolean onTouch(View view, MotionEvent event) {
    final int X = (int) event.getRawX();
    final int Y = (int) event.getRawY();
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
            _xDelta = X - lParams.leftMargin;
            _yDelta = Y - lParams.topMargin;
            break;
        case MotionEvent.ACTION_UP:  
            Intent intent = new Intent(this, Exit_Activity.class);
         startActivity(intent);
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            break;
        case MotionEvent.ACTION_POINTER_UP:
            break;
        case MotionEvent.ACTION_MOVE:
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
            layoutParams.leftMargin = X - _xDelta;
            layoutParams.topMargin = Y - _yDelta;
            layoutParams.rightMargin = -250;
            layoutParams.bottomMargin = -250;
            view.setLayoutParams(layoutParams);
            break;
    }
    _root.invalidate();
    return true;
}

}

如您所见,ACTION_UP当前将用户发送到下一个活动,无论拖动哪个视图。让应用区分观点的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

设置单个视图的ID。单击视图时检索ID。 ID是每个视图的唯一标识。设置ID:

view.setId(x);

点击后,检索ID:

id = view.getId();