3

I want to move a textview inside an imageview such that it should not go outside the imageview. If I touch and move the textview, it should follow my finger. But if i move it ouside the imageview, my textview should not move outside the 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

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Shahbaz Pothiawala
  • 1,175
  • 5
  • 20
  • 38

0 Answers0