Parent 和 Child 片段(嵌套片段)之间的共享元素转换不起作用

Shared Element Transition Not Working Between Parent and Child Fragments (Nested Fragments)

在主要 Activity 中,我有 BottomNavigationView,其中有 3 个不同的 parent 片段。 parent 片段有 recyclerview 并且在 recyclerview 的项目单击上,我正在启动 child 片段以获取有关该项目的更多详细信息。我正在尝试在我的两个片段(parent 和 child)之间实现 Shared Element Transition,但它没有发生。

启动 child 片段没有问题我也检查了过渡名称,它与我分配给适配器中的项目的 child 片段相同。我正在使用 Random class 将转换名称分配给项目,就像在单个 parent 片段中一样 我有很多回收站视图。这是我的代码:

适配器

    final String transition;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        transition = "transition" + new Random().nextInt(9999999);
        viewHolder.image.setTransitionName(transition);
    }
    viewHolder.container.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mCallback.itemClicked(i, book, viewHolder.image, transition);
        }
    });

Parent片段

@Override
public void itemClicked(int pos, Book book, View view, String transition) {
    MainActivity activity = (MainActivity) getActivity();
    ChildFragment myFragment = new ChildFragment();
    Bundle bundle = new Bundle();
    bundle.putString(IntentExtraKeys.TRANSITION_NAME, transition);
    myFragment.setArguments(bundle);
    activity.showFragmentWithTransition(this, myFragment, ChildFragment.class.getName(), view, transition);
}

Activity

public void showFragmentWithTransition(Fragment current, Fragment newFragment, String tag, View sharedView, String sharedElementName) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        current.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
        current.setExitTransition(TransitionInflater.from(this).inflateTransition(android.R.transition.no_transition));
        newFragment.setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
        newFragment.setEnterTransition(TransitionInflater.from(this).inflateTransition(android.R.transition.no_transition));
    }

    FragmentManager manager = current.getChildFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.child_fragment, newFragment, tag);
    transaction.addToBackStack(tag);
    transaction.addSharedElement(sharedView, sharedElementName);
    transaction.commit();
}

default_transition

<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
    <changeTransform />
    <changeBounds />
</transitionSet>

Child片段

    Bundle b = getArguments();
    if (b != null) {
        String transitionName = b.getString(IntentExtraKeys.TRANSITION_NAME);
        Logger.info("opening bundle book fragment:" + transitionName);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            image.setTransitionName(transitionName);
        }
    }

这里是issue的示例工程: https://gitlab.com/iskfaisal/transition-issue

共享元素转换无法使用 FragmentTransaction.add 方法正常工作,因为父片段仍然存在并已恢复。尝试

transaction.replace(R.id.child_fragment, newFragment, tag);

查看 讨论帖以获取更多信息。

我不确定你的其余设置,但要使共享元素转换正常工作,你需要将 setReorderingAllowed(true) 添加到你的片段事务中,如下所示:

FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.child_fragment, newFragment, tag);
transaction.addToBackStack(tag);
transaction.addSharedElement(sharedView, sharedElementName);
transaction.setReorderingAllowed(true); // Add this
transaction.commit();

I am trying to implement Shared Element Transition between my two fragments (parent & child) but it's not happening.

什么都没发生,或者至少看起来什么都没发生,因为您在 default_transition.xml[=110= 中只使用了 <changeTransform/><changeBounds /> ].如果Fragments的边界重合,那么"transit".

就没什么了

但是,如果您向文件添加额外的动画元素,那么过渡实际上是可见的(即使边界重合)。

简介

我创建了一个类似于您的示例项目 - BottomNavigationView,其中 NavHostFragment 包含 2 parent Fragments - DashboardFragmentHomeFragment

最初,DashboardFragment 加载由简单的 RecyclerView 组成的 DashboardListFragment。如果单击任何 RecyclerView 项,则 DashboardFragment 加载 DashboardDetailFragmentDashboardDetailFragmentDashboardListFragment 中的边界重合)。

过渡行为

然后,我几乎重复使用了您的 showFragmentWithTransition(...) 并尝试单击列表中的每个元素以检查是否有任何过渡可见 - 它不是。

因此,我通过添加一个简单的 <slide/> 元素来修改文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<transitionSet>
    <slide/>
    <changeTransform />
    <changeBounds />
</transitionSet>

滑动过渡就在那里。

我还尝试了其他元素,如 <fade/><explode/> 或其他 - 所有这些都工作得很好。

结论

即使转换不可见,也不意味着它没有发生。您应该尝试其他动画元素以查看它是否有效。

更新

由于您为 github 代码提供了 link,我查看了它并使其处于工作状态。我会留给你进一步改进它。

所以,基本上,您的 HomeFragment 布局文件同时包含 RecyclerView 和 child Fragment 的占位符。相反,我将您的 HomeFragment 拆分为 2 个实体 - 一个用于您的 parent Fragment HomeFragment 仅包含任何 child [=38] 的占位符=] 和 HomeFragmentList 包含您之前的 parent 逻辑。

Then, when a picture is selected, HomeFragment replaces your HomeFragmentList with a ChildFragment.而且...有效

这样,您就不需要使用 Activity 来创建 child Fragment,而且它更加独立。

下面,我提供需要修改的相关代码。

代码

HomeFragment(新 parent)

public class HomeFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        HomeFragmentList homeFragmentList = new HomeFragmentList();
        FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.child_fragment, homeFragmentList, homeFragmentList.getClass().getName());
        fragmentTransaction.commit();
    }
}

HomeFragmentList(旧parent)

public class HomeFragmentList extends Fragment implements AdapterListener {
    RecyclerView recyclerView;
    private ArrayList<String> images = new ArrayList<>();

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_home_list, container, false);

        recyclerView = root.findViewById(R.id.recycler_view);
        getImages();
        LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView = root.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(manager);
        AdapterClass adapter = new AdapterClass(this, images);
        recyclerView.setAdapter(adapter);

        return root;
    }

    void getImages() {
        images.add("https://rukminim1.flixcart.com/image/832/832/book/0/1/9/rich-dad-poor-dad-original-imadat2a4f5vwgzn.jpeg?q=70");
        images.add("https://www.seeken.in/wp-content/uploads/2017/06/The-4-Hour-Work-Week.jpeg");
        images.add("https://www.seeken.in/wp-content/uploads/2017/06/Managing-Oneself.jpeg");
        images.add("https://www.seeken.in/wp-content/uploads/2017/07/How-to-Win-Friends-and-Influence-People.jpeg");
        images.add("https://www.seeken.in/wp-content/uploads/2017/07/THINK-LIKE-DA-VINCI-7-Easy-Steps-to-Boosting-your-Everyday-Genius.jpeg");
        images.add("https://www.seeken.in/wp-content/uploads/2017/07/How-To-Stop-Worrying-And-Start-Living.jpg");
        images.add("https://www.seeken.in/wp-content/uploads/2017/08/THE-INTELLIGENT-INVESTOR.jpeg");
        images.add("https://www.seeken.in/wp-content/uploads/2017/08/Awaken-the-Giant-within-How-to-Take-Immediate-Control-of-Your-Mental-Emotional-Physical-and-Financial-Life.jpg");
        images.add("https://www.seeken.in/wp-content/uploads/2017/08/E-MYTH-REVISITED.jpeg");
        images.add("https://images-na.ssl-images-amazon.com/images/I/41axGE4CehL._SX353_BO1,204,203,200_.jpg");
        images.add("https://rukminim1.flixcart.com/image/832/832/book/0/1/9/rich-dad-poor-dad-original-imadat2a4f5vwgzn.jpeg?q=70");

    }

    @Override
    public void itemClicked(int pos, ModelClass object, View view, String transition) {
        MainActivity activity = (MainActivity) getActivity();
        ChildFragment myFragment = new ChildFragment();
        Bundle bundle = new Bundle();
        bundle.putString("IMAGE_URL", object.getItem(pos));
        bundle.putInt("POSITION", pos);
        bundle.putString("TRANSITION_NAME", transition);
        myFragment.setArguments(bundle);
        Log.i("HOME FRAGMENT-DEBUG", transition + "/" + view.getTransitionName());
        showFragmentWithTransition(getParentFragment(), myFragment, ChildFragment.class.getName(), view, transition);
    }

    public void showFragmentWithTransition(Fragment current, Fragment _new, String tag, View sharedView, String sharedElementName) {

        FragmentManager manager = current.getChildFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        if (sharedView != null && sharedElementName != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                current.setSharedElementReturnTransition(TransitionInflater.from(getContext()).inflateTransition(R.transition.default_transition));
                current.setExitTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.no_transition));
                _new.setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(R.transition.default_transition));
                _new.setEnterTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.no_transition));
                transaction.addSharedElement(sharedView, sharedElementName);
                Log.i("ACTIVITY-DEBUG", sharedElementName + "/" + sharedView.getTransitionName());
            }
        }
        transaction.replace(R.id.child_fragment, _new, tag);
        transaction.addToBackStack(tag);
        transaction.commit();
    }
}

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/child_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

fragment_home_list.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFF">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/home_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:layout_marginLeft="9dp"
                android:layout_marginRight="9dp">


                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/recycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:orientation="vertical">

                </androidx.recyclerview.widget.RecyclerView>

            </RelativeLayout>

        </androidx.core.widget.NestedScrollView>

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#FFF">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/z_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:elevation="4dp">

                <RelativeLayout
                    android:id="@+id/header_container"
                    android:layout_width="match_parent"
                    android:layout_height="56dp">

                    <ImageView
                        android:id="@+id/logo"
                        android:layout_width="30dp"
                        android:layout_height="30dp"
                        android:layout_marginRight="10dp"
                        android:layout_centerVertical="true"
                        android:layout_alignParentLeft="true"
                        android:src="@mipmap/ic_launcher_round"
                        android:contentDescription="@string/app_name" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_toRightOf="@+id/logo"
                        android:textColor="#000"
                        android:textSize="16sp"
                        android:text="Home" />

                </RelativeLayout>

            </androidx.appcompat.widget.Toolbar>

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

    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</RelativeLayout>

备注

请注意 <changeTransform/><changeBounds /> 的过渡是可见的,因为 HomeFragmentList 中选定的 View 的边界与 [=118= 中的不同] Fragment