在imageview边界内移动textview

时间:2015-06-05 06:04:08

标签: textview move drag motionevent ontouch

我想在imageview中移动textview,使其不应超出imageview。如果我触摸并移动文本视图,它应该跟着我的手指。但是,如果我移动它在imageview上,我的textview不应该移动到imageview之外。

public boolean onTouch(View view, MotionEvent event) 
{
    final int X = (int) event.getRawX();
    final int Y = (int) event.getRawY();
    RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)view.getLayoutParams();
    imgrect=new Rect(parent.getLeft(), parent.getTop(), parent.getRight(), parent.getBottom());

    switch (event.getAction()) 
    {
        case MotionEvent.ACTION_DOWN:
            x = X - lParams.leftMargin;
            y = Y - lParams.topMargin;
            break;
        case MotionEvent.ACTION_UP:
            break;
        case MotionEvent.ACTION_MOVE:
            int w=parent.getWidth() - imgrect.left-view.getWidth();
            int h=parent.getHeight() - imgrect.top;//-view.getHeight();

            if(lParams.leftMargin<1)
            {
                lParams.leftMargin = 1;
                    view.setLayoutParams(lParams);
            }
            else if(lParams.topMargin<1)
            {
                lParams.topMargin = 1;
                    view.setLayoutParams(lParams);
            }
            else if(lParams.leftMargin>w)
            {
                lParams.leftMargin = w-1;
                    view.setLayoutParams(lParams);
            }
            else if(lParams.topMargin>h)
            {
                lParams.topMargin = h-1;
                    view.setLayoutParams(lParams);
            }
            else
            {
                lParams.leftMargin = X - x;
                lParams.topMargin = Y - y;
                    view.setLayoutParams(lParams);
            }
            break;
    }
parent.invalidate();
    return false;
}

enter image description here

0 个答案:

没有答案