限制ImageView的位置

时间:2015-01-04 20:09:47

标签: android imageview position layoutparams

我创建了一个可以在屏幕上拖动的ImageView。但有时它会离开屏幕,我正试图解决它。如何定义imageview的x和y坐标的最小和最大限制?

我试过了,但失败了:

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fase);

    final ImageView balls = (ImageView)findViewById(R.id.ball);
    LayoutParams layoutParams = (LayoutParams) balls.getLayoutParams();

    changeScreen = (Button)findViewById(R.id.button);
    changeScreen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent Ts2 = new Intent(Fase.this, Over.class);
            Fase.this.startActivity(Ts2);
            Fase.this.finish();
        }
    });

    if (balls.getLeft()<400)
    {
        layoutParams.leftMargin = 400;
    }
    if (balls.getLeft() > 500)
    {
        layoutParams.leftMargin = 500;
    }
    if (balls.getTop() <40)
    {
        layoutParams.topMargin = 40;
    }
    if (balls.getTop() > 500)
    {
        layoutParams.topMargin = 500;
    }

   windowwidth = getWindowManager().getDefaultDisplay().getWidth();
    windowheight = getWindowManager().getDefaultDisplay().getHeight();

    balls.setOnTouchListener(new View.OnTouchListener() {   // this allows me to drag the imageView

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) fish.getLayoutParams();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    break;
                case MotionEvent.ACTION_MOVE:
                    System.out.println(balls.getLeft());
                    int x_cord = (int) event.getRawX();
                    int y_cord = (int) event.getRawY();

                    if (x_cord > windowwidth) {
                        x_cord = windowwidth;
                    }
                    if (y_cord > windowheight) {
                        y_cord = windowheight;
                    }

                    layoutParams.leftMargin = x_cord - 50; 
                    layoutParams.topMargin = y_cord - 150; 

                    balls.setLayoutParams(layoutParams);
                    break;
                default:
                    break;
            }
            return true;
        }
    });
   }
  • OBS:代码的这一部分是在“onCreate”方法中。这是一个问题吗?

0 个答案:

没有答案