Анимация, уберите мерцание, когда вид. Видимость (ушел) и другой вид занимают место - PullRequest
0 голосов
/ 20 февраля 2020

Я имею дело с анимацией, и я новичок в этом. У меня есть эта структура в XML файле:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:focusable="true"
        android:orientation="vertical"
        android:padding="10dp"
        android:background="@color/colorAccent"
        android:layout_gravity="center">

        <TextView
            android:id="@+id/textViewT"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Some Text"
            android:textSize="18sp"
            android:textStyle="bold"
            android:textColor="@color/colorPrimaryDark"
            android:gravity="center"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Something"
            android:textSize="12sp"
            android:textColor="@color/colorPrimary"
            android:gravity="center"/>

    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingStart="10dp"
        android:paddingEnd="10dp"
        android:scrollbars="vertical" />

Анимация:

<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">

<translate
    android:duration="300"
    android:fromYDelta="0"
    android:toYDelta="-100%"/>

И мой MainActivity выглядит так:

public class MainActivity extends AppCompatActivity {

MyRecyclerViewAdapter adapter;
boolean animationOnOff;
LinearLayout ll;
Animation animScroll;

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

    ArrayList<String> animalNames = new ArrayList<>();
    animalNames.add("Horse");
    ....

    animationOnOff = true;
    ll = findViewById(R.id.linearLayout1);
    animScroll = AnimationUtils.loadAnimation(this, R.anim.total_gasto_hide);
    animScroll.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            ll.animate().alpha(0).setDuration(0).withEndAction(new Runnable() {
                @Override
                public void run() {
                    ll.setVisibility(View.GONE);
                }
            });
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
    RecyclerView recyclerView = findViewById(R.id.list);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new MyRecyclerViewAdapter(this, animalNames);
    recyclerView.setAdapter(adapter);
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if(dy > 0) {
                if(animationOnOff) {
                    ll.startAnimation(animScroll);
                    animationOnOff = false;
                }
            } else {

            }
        }
    });
}
}

Этот код должен поднять linearLayout1 и исчезнуть через 300 мс с visibility(view.GONE), пока все хорошо. Проблема состоит в том, что представление переработчика не увязает с этой анимацией, и когда linearLayout1 исчезает, переработчик мгновенно получает положение исчезнувшего вида (делая некоторый эффект моргания). Gif ниже:

Gif

Итак, мой вопрос, как я могу сделать это, чтобы устранить этот эффект мерцания и добиться эффекта плавной интерполяции, когда linearLayout1 ушел?

Ответы [ 2 ]

1 голос
/ 20 февраля 2020

Android может обрабатывать анимацию для вас по умолчанию. Просто добавьте android:animateLayoutChanges="true" к вашему родителю LinearLayout, и видимость будет анимированной.

0 голосов
/ 20 февраля 2020

Я предлагаю вам использовать CoordinatorLayout с CollapsingToolbarLayout и изменить приложение : layout_scrollFlags в соответствии с вашими потребностями

Это будет поможет вам удалить код детали котла, который вы добавили в свою активность

 <androidx.coordinatorlayout.widget.CoordinatorLayout 
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/cl_newdashboard"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            app:elevation="2dp">

            <!--Toolbar here if you don't want to collapse it-->

        <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways">

            <!--COLLAPSING UI to be added here-->

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>


    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_prescriptions"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <!--REST OF THE VIEW-->

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Часть пользовательского интерфейса, которая окажется внутри CollapsingToolbarLayout , будет скрыта, когда RecyclerView прокручивается,

...