у меня есть одна проблема с анимацией перетаскивания - PullRequest
3 голосов
/ 26 сентября 2019

Я реализую способ перемещения вида по экрану, но мне нужно знать, как проверить, чтобы он не выходил за края экрана.

изображение

изображение 2

я не хочу, чтобы это произошло

изображение 3

код моей активности

public class MainActivity extends AppCompatActivity {


private ImageView img;
private RelativeLayout relativeLayout;
private View rootLayout;
private int _xDelta;
private int _yDelta;
private TextView textView;

private int modificarX = 350;
private int modificarY = 350;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = findViewById(R.id.get);
    rootLayout = (View) findViewById(R.id.view_root);
    img = (ImageView) rootLayout.findViewById(R.id.imageView);

    final RelativeLayout.LayoutParams[] layoutParams = {new RelativeLayout.LayoutParams(600, 600)};
    img.setLayoutParams(layoutParams[0]);
    img.setOnTouchListener(new ChoiceTouchListener());

}

private final class ChoiceTouchListener implements View.OnTouchListener {
    public boolean onTouch(View view, MotionEvent event) {

        final int X = (int) event.getRawX();
        final int Y = (int) event.getRawY();
        textView.setText("X: " + X + " Y: " + Y);
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                _xDelta = X - lParams.leftMargin;
                _yDelta = Y - lParams.topMargin;

                break;
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                break;
            case MotionEvent.ACTION_POINTER_UP:
                break;
            case MotionEvent.ACTION_MOVE:
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
                        .getLayoutParams();

                    layoutParams.leftMargin = X - _xDelta - 10;
                    layoutParams.topMargin = Y - _yDelta;
                    layoutParams.rightMargin = -250;
                    layoutParams.bottomMargin = -250;
                    view.setLayoutParams(layoutParams);
                    Toast.makeText(MainActivity.this, "X: " + X + " Y: " + Y, Toast.LENGTH_LONG).show();
                    rootLayout.getRight();
                break;
        }
        rootLayout.invalidate();
        return true;
    }
}

}

кто-нибудь, помогите мне, пожалуйста, мне это нужно, спасибо

1 Ответ

2 голосов
/ 26 сентября 2019

Прежде всего вы должны получить ширину и высоту экрана

int w = getResources().getDisplayMetrics().widthPixels
int h = getResources().getDisplayMetrics().heightPixels

Или rootLayout (сделайте это, когда ваш rootLayout был размечен, иначе вы получите 0):

int w = rootLayout.getWidth();
int h = rootLayout.getHeight();

// or if view haven't been laid out yet:
rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        rootLayout.getViewTreeObserver()
                .removeOnGlobalLayoutListener(this);

        int w = rootLayout.getWidth();
        int h = rootLayout.getHeight();
    }
});

Затем вы должны проверить границы представления так, чтобы left > 0, right < w, bottom < h и top > 0.

layoutParams.leftMargin = Math.max(0, Math.min(rootLayout.getWidth() - view.getWidth(), X - _xDelta - 10))
layoutParams.topMargin = Math.max(0, Math.min(rootLayout.getHeight() - view.getHeight(), Y - _yDelta))

Чтобы объяснить, что здесь происходит, давайте возьмемэкран 500x800 пикселей, а вид 100x100 пикселей.У нас есть 3 случая, 2 из которых выходят за границы, а 1 находится в пределах.

// TEST 1
int out1X = -50; //x coordinate of the view
int out1Y = -50; //y coordinate of the view
layoutParams.leftMargin = Math.max(0, Math.min(w - 100/*view width*/, out1X))
layoutParams.topMargin = Math.max(0, Math.min(h - 100/*view height*/, out1Y))
// here we have for leftMargin max(0, min(400, -50)) => max(0, -50) => 0 your view won't go further than 0
// for topMargin: max(0, min(700, -50)) => max(0, -50) => 0

// TEST 2
int out2X = 650; //x coordinate of the view
int out2Y = 950; //y coordinate of the view
layoutParams.leftMargin = Math.max(0, Math.min(w - 100, out2X))
layoutParams.topMargin = Math.max(0, Math.min(h - 100, out2Y))
// leftMargin: max(0, min(400, 650)) => max(0, 400) => 400 
// topMargin: max(0, min(700, 950)) => max(0, 700) => 700

// TEST 3
int inX = 50; //x coordinate of the view
int inY = 50; //y coordinate of the view
layoutParams.leftMargin = Math.max(0, Math.min(w - 100, inX))
layoutParams.topMargin = Math.max(0, Math.min(h - 100, inY))
// leftMargin: max(0, min(400, 50)) => max(0, 50) => 50
// topMargin: max(0, min(700, 50)) => max(0, 50) => 50
// in this case we get our original coordinates

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...