Android 在安卓系统中,停止将对象移出屏幕

Android 在安卓系统中,停止将对象移出屏幕,android,Android,我在安卓系统中通过onTouch移动一个对象,但是该对象离开了屏幕,我如何才能阻止它 case MotionEvent.ACTION_MOVE: DisplayMetrics dm = getResources().getDisplayMetrics(); final int parentHeight = dm.heightPixels; final int parentWidth = dm.widthPixels; Relati

我在安卓系统中通过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{
只要使用基础数学

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

最大上边距是父对象的容器高度减去正在移动的视图高度,当然大于零

这里有一个例子,我使用整个屏幕大小作为父容器的维度,调整它以满足您的需要

// 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;

getResources()方法中应该包含什么?Android中的每个视图默认都有
getResources()
方法。。。。您的代码是否在视图类中?请通过编辑您的问题来扩展代码。您的类已经有了一个
getResources()
方法,因为它是一个视图。左边距和上边距现在可以工作了,但是右边距和下边距呢?我已经更改了上面的移动选项