Анимация штрих-кода, порт для ConstraintLayout - PullRequest
0 голосов
/ 14 января 2020

Я нашел этот код для анимации красной полосы (сканер штрих-кода). Однако это было сделано для относительного расположения с фиксированными размерами. Мне нужно найти значение Float (относительно контейнера) вместо фиксированного значения.

Здесь макет:

    <RelativeLayout
        android:id="@+id/trackBox"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerInParent="true"
        android:background="@drawable/background_border"
        app:layout_constraintBottom_toTopOf="@+id/guidelineBarcodeScanner04"
        app:layout_constraintEnd_toStartOf="@+id/guidelineBarcodeScanner01"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="@+id/guidelineBarcodeScanner02"
        app:layout_constraintTop_toTopOf="@+id/guidelineBarcodeScanner03"
        app:layout_constraintVertical_bias="0.0">

        <RelativeLayout
            android:id="@+id/midLine"
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="#FF0000" />

    </RelativeLayout>

Где midLine - красная полоса, а trackBox - белая граница поле, где полоса должна скользить вверх и вниз.

А вот фактический код:

    public void slideToAbove() {

        Animation slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, -300);
        slide.setDuration(2000);

        midLine.startAnimation(slide);

        slide.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                midLine.clearAnimation();
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                        midLine.getWidth(), midLine.getHeight());
                lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                midLine.setLayoutParams(lp);

                slideToDown();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    public void slideToDown() {

        Animation slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 300);
        slide.setDuration(2000);

        midLine.startAnimation(slide);

        slide.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                midLine.clearAnimation();
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                        midLine.getWidth(), midLine.getHeight());
                lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                midLine.setLayoutParams(lp);

                slideToAbove();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

Значение, которое нужно найти, на самом деле является фиксированным 300. Поле ограничено (в процентах от таким образом, фиксированное значение совсем не годится.

Я только что попробовал trackBox.getHeight (), но это не так.

Только что попробовал:

        int i;
        i = trackBox.getBottom() - trackBox.getTop();

не работает ...

1 Ответ

0 голосов
/ 15 января 2020

Наконец-то замечательный сканер штрих-кода в ConstraintLayout!

Прежде всего вам необходимо создать 2 анимированных файла в папке Res-> anim:

barcode_to_above_anim. xml

<?xml version="1.0" encoding="utf-8"?>
<!-- translating button from bottomt to top -->
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="97%p" android:toYDelta="3%p"
        android:duration="2000"
        />
</set>

barcode_to_down_anim. xml

<?xml version="1.0" encoding="utf-8"?>
<!-- translating button from top to bottom -->
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="3%p" android:toYDelta="97%p"
        android:duration="2000"
        />
</set>

Тогда ваша деятельность должна быть похожа на мою:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayoutBarcodeScanner"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#292929"
    android:screenOrientation="landscape">

    <SurfaceView
        android:id="@+id/surfaceViewBarcodeScanner"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="16:9"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <RelativeLayout
        android:id="@+id/trackBox"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerInParent="true"
        android:background="@drawable/background_border"
        android:paddingStart="2dp"
        android:paddingLeft="2dp"
        android:paddingEnd="2dp"
        android:paddingRight="2dp"
        app:layout_constraintBottom_toTopOf="@+id/guidelineBarcodeScanner04"
        app:layout_constraintEnd_toStartOf="@+id/guidelineBarcodeScanner01"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="@+id/guidelineBarcodeScanner02"
        app:layout_constraintTop_toTopOf="@+id/guidelineBarcodeScanner03"
        app:layout_constraintVertical_bias="0.0">

        <RelativeLayout
            android:id="@+id/midLine"
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="#FF0000" />

    </RelativeLayout>

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guidelineBarcodeScanner01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.8" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guidelineBarcodeScanner02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.2" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guidelineBarcodeScanner03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.25" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guidelineBarcodeScanner04"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.75" />

</androidx.constraintlayout.widget.ConstraintLayout>

И, наконец, код, который вам нужен в вашей деятельности. java: Объявление

public class BarcodeScannerActivity extends Activity {

    RelativeLayout midLine, trackBox;
    //your other code

Ссылка на объекты и запуск первой анимации:

    private void init(){
        setContentView(R.layout.barcodescanner_activity);
        midLine = findViewById(R.id.midLine);
        trackBox = findViewById(R.id.trackBox);
        slideToDown();
    }

Давайте оживим!:

    public void slideToAbove() {
        Animation slide= AnimationUtils.loadAnimation(getBaseContext(), R.anim.barcode_to_above_anim);
        midLine.startAnimation(slide);

        slide.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                slideToDown();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    public void slideToDown() {

        Animation slide= AnimationUtils.loadAnimation(getBaseContext(), R.anim.barcode_to_down_anim);
        midLine.startAnimation(slide);

        slide.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                slideToAbove();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

Я должен вас заверить, это действительно крутой эффект! Надеюсь помочь кому-нибудь создать крутой эффект сканирования штрих-кода.

Обратите внимание:

    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="97%p" android:toYDelta="3%p"
        android:duration="2000"
    />

% p означает процент по отношению к родительскому представлению (или контейнеру). или экран).

...