2017-02-23 12 views
2

Я пытаюсь реализовать общий переход в своем приложении. Я хочу ImageView в RecyclerView, который будет присутствовать в следующем фрагменте, чтобы иметь общий переход из RecyclerView в фрагмент. Но он не работает. Вот как я это сделал.Shared Transition не работает recyclerview для фрагмента

макет элемент Ресайклер в

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 

    <ImageView 
     android:id="@+id/iv_cover" 
     android:layout_width="match_parent" 
     android:layout_height="150dp" 
     android:scaleType="centerCrop" 
     android:transitionName="cover" 
     android:src="@drawable/ic_check_circle" /> 

    <View 
     android:layout_width="match_parent" 
     android:layout_height="150dp" 
     android:background="#30000000" /> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="150dp"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_above="@id/tv_title" 
      android:layout_marginBottom="5dp" 
      android:layout_marginLeft="10dp" 
      android:layout_marginRight="10dp" 
      android:background="@color/colorPrimary" 
      android:paddingLeft="5dp" 
      android:paddingRight="5dp" 
      android:text="BBC" 
      android:textAppearance="@style/Base.TextAppearance.AppCompat.Caption" 
      android:textColor="#fff" 
      android:textSize="16dp" /> 

     <TextView 
      android:id="@id/tv_title" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentBottom="true" 
      android:layout_marginBottom="10dp" 
      android:layout_marginLeft="10dp" 
      android:layout_marginRight="10dp" 
      android:background="@color/colorPrimary" 
      android:maxLines="3" 
      android:paddingLeft="5dp" 
      android:paddingRight="5dp" 
      android:text="NEWS TITLE" 
      android:textAppearance="@style/TextAppearance.AppCompat.Caption" 
      android:textColor="#fff" 
      android:textSize="20sp" /> 
    </RelativeLayout> 
</RelativeLayout> 

Фрагмент макета

<?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" 
    android:orientation="vertical"> 

    <ImageView 
     android:id="@+id/iv_cover" 
     android:transitionName="cover" 
     android:layout_width="match_parent" 
     android:layout_height="200dp" 
     android:scaleType="centerCrop" /> 

    <TextView 
     android:id="@+id/tv_title" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

    <TextView 
     android:id="@+id/tv_description" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

    <Button 
     android:id="@+id/btn_story" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Read Full Story" 
     android:layout_gravity="center"/> 
</LinearLayout> 

Вот Java-код, который я использовал

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
      //ImageView ivCover = (ImageView) getActivity().findViewById(R.id.iv_cover); 
      getActivity().getSupportFragmentManager() 
        .beginTransaction() 
        .replace(android.R.id.content, feedFragment, "Feed") 
        .addSharedElement(cover, "cover") 
        .addToBackStack("Feed") 
        .commit(); 
     } 

Вот Fragment код

@Override 
    public void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     postponeEnterTransition(); 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
      setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.move)); 
     } 
    } 
private void loadData() { 
    String title = null; 
    String description = null; 
    String urlToImage = null; 
    String url = null; 
    try { 
     title = getArguments().getString(ARG_PARAM1); 
     description = getArguments().getString(ARG_PARAM2); 
     url = getArguments().getString(ARG_PARAM3); 
     urlToImage = getArguments().getString(ARG_PARAM4); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    if (title != null) 
     tvTitle.setText(title); 
    if (tvDescription != null) 
     tvDescription.setText(description); 
    if (urlToImage != null) 
     Picasso.with(getActivity()).load(urlToImage).into(ivCover, new Callback() { 
      @Override 
      public void onSuccess() { 
       startPostponedEnterTransition(); 
      } 

      @Override 
      public void onError() { 
       startPostponedEnterTransition(); 
      } 
     }); 
} 

Вот стиль

<!-- Base application theme. --> 
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
    <!-- Customize your theme here. --> 
    <item name="colorPrimary">@color/colorPrimary</item> 
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item> 
    <item name="colorAccent">@color/colorAccent</item> 
    <item name="android:windowContentTransitions">true</item> 
</style> 

Что я делаю неправильно? Пожалуйста, направляйте меня сюда. Благодаря

ответ

0

В вашем onBindViewHolder, добавьте следующую строку:

holder.ivCover.setTransitionName("trans_image" + position); 

Каждый Общий элемент должен иметь уникальное имя перехода.

Таким образом, вместо .addSharedElement(cover, "cover"),

написать .addSharedElement(cover, imageTransitionName)

где

imageTransitionName = rv_imageView.getTransitionName(); 

и, в зависимости от реализации (onClickListener потребуется view.findViewById() вместо getActivity(). ..),

ImageView rv_imageView =(ImageView) getActivity().findViewById(R.id.iv_cover);

Также вы можете попробовать fade или slide_right или свой собственный переход.

Все это будет работать в случае, когда вы щелкните элемент и новый подробный фрагмент появляется

Так что вам нужно отправить imageTransitionName в пачке ... и получить этот аргумент в деталях (скажем) фрагмент, такой как

String imageTransitionName = bundle.getString("TRANS_NAME"); 
view.findViewById(R.id.iv_cover).setTransitionName(imageTransitionName); 
+0

Это работает как-то, но когда я нажимаю кнопку «Назад». Он не анимируется, как это было, когда я открыл фрагмент. Я имею в виду, что на спине нет анимации, но я хочу сохранить то, что произошло в начале. –

+0

Обратный образ анимации как-то не работает в recyclerview-v7: 25.1.1. Так что несите его или ждите, пока он не будет исправлен Google. Хотя вы все еще можете попробовать попробовать, добавив еще одну строку setSharedElementReturnTransition ... –

+0

И если это того стоит, пожалуйста, примите ответ и сделайте честь. –

Смежные вопросы