停止移动对象在android中离开屏幕

时间:2015-01-24 02:52:11

标签: android

我在android中通过onTouch移动一个对象,但是该对象离开了屏幕,我怎么能阻止它呢?

case MotionEvent.ACTION_MOVE:
        DisplayMetrics dm = getResources().getDisplayMetrics();
        final int parentHeight = dm.heightPixels;
        final int parentWidth = dm.widthPixels;

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) this
                .getLayoutParams();
        layoutParams.leftMargin = Math.min(Math.max(0, (x - m_X)),
                parentWidth - this.getWidth());
        layoutParams.topMargin = Math.min(Math.max(0, (y - m_Y)),
                parentHeight - this.getHeight());
        layoutParams.rightMargin = Math.min(Math.max(0, (x - m_W)),
                parentWidth - this.getWidth());
        layoutParams.bottomMargin = Math.min(Math.max(0, (y - m_Z)),
                parentHeight + this.getHeight());
        this.setLayoutParams(layoutParams);

结构是:

public FTFLImageView(Context context) {
        super(context);
        init();
    }

    public FTFLImageView(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
    }

    private void init() {
        // TODO Auto-generated method stub
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                150, 150);
        this.setImageResource(R.drawable.ic_launcher);
        this.setLayoutParams(layoutParams);

    }

,课程开始时为:

public class FTFLImageView extends ImageView implements OnTouchListener{

1 个答案:

答案 0 :(得分:0)

只需使用基本数学。

最大左边距是父母的容器宽度减去您正在移动的视图的宽度 - 当然大于零。

最大上边距是父母的容器高度减去您正在移动的视图的高度 - 当然大于零。

以下是一个例子,我使用整个屏幕尺寸作为父容器的尺寸,根据您的需要进行调整。

// using display size here, it's better to use the parent container's dimensions!
DisplayMetrics dm = getResources().getDisplayMetrics(); 

final int parentHeight = dm.heightPixels;
final int parentWidth  = dm.widthPixels;

...

case MotionEvent.ACTION_MOVE:
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)v.getLayoutParams();
            layoutParams.leftMargin = Math.min(Math.max(0, (x - m_X)), parentWidth-v.getWidth());
            layoutParams.topMargin = Math.min(Math.max(0, (y - m_Y)), parentHeight-v.getHeight())
            v.setLayoutParams(layoutParams);
            Toast.makeText(context,"X="+x+"Y="+y, 5000).show();
            break;