Как непрерывно перемещать объект в Android Studio - PullRequest
0 голосов
/ 20 июня 2020

Как постоянно перемещать ImageView в Android Studio, когда кнопка удерживается, но останавливаться, когда по ней больше не нажимают? Другими словами: как определить, не нажата ли кнопка§, или напрямую определить, удерживается ли она. Спасибо за помощь

Ответы [ 2 ]

0 голосов
/ 20 июня 2020

Чтобы определить нажатие / отпускание кнопки (вниз / вверх), используется TouchListener.

    imageView = findViewById(R.id.image);
    button = findViewById(R.id.button);
    root_layout = findViewById(R.id.root_layout); //parent layout

    final Handler handler = new Handler();
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            float x = imageView.getX();
            if(x > root_layout.getWidth())
                x = 0;
            else
                x += 6; //Increase value of '6' to move the imageView faster
            imageView.setX(x);

            handler.postDelayed(this,0); //increase delay '0' if facing lag. 
            // This is the rate at which the x value of our imageView is being updated
            
        }
    };

    button.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    handler.post(runnable); //Start moving imageView
                    break;
                case MotionEvent.ACTION_UP:
                    handler.removeCallbacks(runnable); //Stop moving imageView
                    break;
            }
        return true;
        }
    });

0 голосов
/ 20 июня 2020

Попробуйте это решение

Шаг 1: - необходимо определить папку anim в папке res.

теперь поместите файл rotate. xml в папку anim.

rotate.xml файл

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="600"
        android:repeatMode="restart"
        android:repeatCount="infinite"
        android:interpolator="@android:anim/cycle_interpolator"/>

</set>

Шаг 2: - Программно объявить анимацию

// Animation
    Animation animFadein;

in onCreate()
// load the animation
        animFadein = AnimationUtils.loadAnimation(getApplicationContext(),
                R.anim.rotate);

Шаг 3: - Определить пользователя нажмите вот так, чтобы запустить и остановить анимацию

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            //start animation here
           imageView.startAnimation(animFadein);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            // stop animation here
             imageView.stopAnimation(animFadein);
        }
        return true;
    }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...