Как сделать так, чтобы замена фрагмента и дополнительное изменение пользовательского интерфейса происходили одновременно? - PullRequest
0 голосов
/ 14 июля 2020

В моем MainActivity есть TabLayout, который я показываю (View.VISIBILE), когда загружаются определенные фрагменты (например, тип A), и скрывается (View.GONE), когда загружаются другие фрагменты (например, тип B).

Теперь при переходе между фрагментами типа A и типа B - TabLayout и фрагмент не загружаются вместе. Сначала становится видимым TabLayout, и предыдущий фрагмент сдвигается вниз, затем новый фрагмент заменяет старый фрагмент. Конечно, это происходит за миллисекунды, но при внимательном рассмотрении наблюдается некоторый видимый эффект.

Как я могу убедиться, что изменение видимости TabLayout и замена фрагмента происходят вместе?

Вот код для загрузки фрагментов в MainActivity. java:

    ...
    private View mTitleWithTabs = findViewById(R.id.title_and_hometabs);
    ...

    @UiThread
    public void loadFragment(Fragment fragment) {

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction
                .add(R.id.frameLayout, fragment)
                .addToBackStack(null)
                .commit();

        if (/* type A fragment */) {
            setTabsHomeButtonSelected(true);  // setting an ImageView as selected or not
            scrollAndSelectTabAtPositionOnlyUI(0);
            mTitleWithTabs.setVisibility(View.VISIBLE);
        } else {
            setTabsHomeButtonSelected(false);
            mTitleWithTabs.setVisibility(View.GONE);
        }
    }

Вот соответствующий код из activity_main. xml

    ...
    <include
        android:id="@+id/title_and_hometabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/title_with_hometabs"/>

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/exo_mini"
        android:layout_below="@id/title_and_hometabs"/>
   ...

Вот title_with_hometabs. xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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/title_with_hometabs"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:showIn="@layout/activity_main">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:orientation="horizontal"
        android:weightSum="1">

        <TextView
            android:id="@+id/title"
            android:paddingStart="35dp"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight=".90"
            android:gravity="center"
            android:text="@string/app_name"
            android:textColor="@color/colorViewAll"
            android:textSize="@dimen/text_size_22" />


        <ImageView
            android:id="@+id/search_browser"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_gravity="center_vertical"
            android:layout_weight=".10"
            android:src="@drawable/ic_search_black_14dp" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorDivider" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:orientation="horizontal">

        <RelativeLayout
            android:layout_width="?actionBarSize"
            android:layout_height="42dp"
            android:gravity="center">

            <ImageView
                android:id="@+id/home_button_tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:src="@mipmap/home" />
        </RelativeLayout>

        <View
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="@color/colorDivider" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs_list"
            android:layout_height="42dp"
            android:layout_width="match_parent"
            app:tabBackground="@android:color/transparent"
            app:tabRippleColor="@null"
            app:tabMode="scrollable"
            app:tabIndicatorColor="@android:color/holo_red_dark"
            app:tabSelectedTextColor="@android:color/holo_blue_dark"
            app:tabTextAppearance="@style/CustomTabLanguages"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="@color/colorDivider" />
    </LinearLayout>
</LinearLayout>

1 Ответ

0 голосов
/ 16 июля 2020

У меня сработало использование getSupportFragmentManager (). ExecutePendingTransactions () после вызова commit () внутри метода loadFragment () в MainActivity. java.

Это потому, что задержка между дополнительными Элемент пользовательского интерфейса в MainActivity и загрузка фрагмента происходили из-за того, что FragmentManager.commit () был асинхронным.

Другие способы, которые я исследовал и не сработал:

  • Использование FragmentManager.commitNow () не работает, потому что мне нужен backstack.
  • Использование FragmentManager.runOnCommit (additionUIElementChangeRunnable) также не позволяет добавить транзакцию фрагмента в backstack.

Примечание. FragmentManager.commitNow () не позволяет использовать backstack, потому что гарантия упорядочивания в backstack не может быть предоставлена, когда commitNow используется с фиксацией.

...