gpt4 book ai didi

android - 共享元素过渡 imageview 变白

转载 作者:行者123 更新时间:2023-12-04 12:43:03 27 4
gpt4 key购买 nike

我正在使用 RecyclerView 到 ViewPager 共享元素转换。问题是,当 viewpager 被分页到另一个图像时,在返回到 recyclerview 后,首先被动画化的 imageview 是白色的。

enter image description here

启动viewpager:

FragmentTransaction fragmentTransaction = getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.addSharedElement(view, name)
.hide(recyclerFragment)
.add(R.id.main_frameLayout, viewpagerFragment, tag)
.commit();

返回到 recyclerview fragment :

FragmentTransaction fragmentTransaction = getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.addSharedElement(view, name)
.remove(viewpagerFragment)
.show(recyclerFragment)
.commit();

编辑:请注意,我知道这些位置并且我正在正确设置转换名称。

最佳答案

我已经使用“Recyclerview + ViewPager + SharedTransition”为您创建了示例

首先让我告诉您代码中的问题是,您正在添加和删除 fragment 而不是替换 fragment 当启动 viewpager 并从 viewpager 返回时。此外,您还必须采用整数变量来保存 recyclerview 和 viewpager 的当前位置。

下面是 gif 示例,展示了我取得的成就:

enter image description here

首先在您的 MainActivity 中将“currentPosition”作为 int,如下所示:

public static int currentPosition;

然后创建将包含图像数组的抽象“ImageData”类,如下所示:

abstract class ImageData {
static final int[] IMAGE_DRAWABLES = {
R.drawable.android1,
R.drawable.android2,
R.drawable.android3,
R.drawable.android4,
R.drawable.android5,
};
}

现在创建将在 recyclerView 中显示图像列表的“GridAdapter”:

/**
* A fragment for displaying a grid of images.
*/
public class GridAdapter extends RecyclerView.Adapter<ImageViewHolder> {

/**
* A listener that is attached to all ViewHolders to handle image loading events and clicks.
*/
private interface ViewHolderListener {

void onLoadCompleted(ImageView view, int adapterPosition);

void onItemClicked(View view, int adapterPosition);
}

private final RequestManager requestManager;
private final ViewHolderListener viewHolderListener;

/**
* Constructs a new grid adapter for the given {@link Fragment}.
*/
public GridAdapter(Fragment fragment) {
this.requestManager = Glide.with(fragment);
this.viewHolderListener = new ViewHolderListenerImpl(fragment);
}

@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.image_card, parent, false);
return new ImageViewHolder(view, requestManager, viewHolderListener);
}

@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
holder.onBind();
}

@Override
public int getItemCount() {
return IMAGE_DRAWABLES.length;
}

private static class ViewHolderListenerImpl implements ViewHolderListener {

private Fragment fragment;
private AtomicBoolean enterTransitionStarted;

ViewHolderListenerImpl(Fragment fragment) {
this.fragment = fragment;
this.enterTransitionStarted = new AtomicBoolean();
}

@Override
public void onLoadCompleted(ImageView view, int position) {
// Call startPostponedEnterTransition only when the 'selected' image loading is completed.
if (MainActivity.currentPosition != position) {
return;
}
if (enterTransitionStarted.getAndSet(true)) {
return;
}
fragment.startPostponedEnterTransition();
}

@Override
public void onItemClicked(View view, int position) {
// Update the position.
MainActivity.currentPosition = position;

// Exclude the clicked card from the exit transition (e.g. the card will disappear immediately
// instead of fading out with the rest to prevent an overlapping animation of fade and move).
((TransitionSet) fragment.getExitTransition()).excludeTarget(view, true);

ImageView transitioningView = view.findViewById(R.id.card_image);
fragment.getFragmentManager()
.beginTransaction()
.setReorderingAllowed(true) // Optimize for shared element transition
.addSharedElement(transitioningView, transitioningView.getTransitionName())
.replace(R.id.fragment_container, new ImagePagerFragment(), ImagePagerFragment.class
.getSimpleName())
.addToBackStack(null)
.commit();
}
}

/**
* ViewHolder for the grid's images.
*/
static class ImageViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {

private final ImageView image;
private final RequestManager requestManager;
private final ViewHolderListener viewHolderListener;

ImageViewHolder(View itemView, RequestManager requestManager,
ViewHolderListener viewHolderListener) {
super(itemView);
this.image = itemView.findViewById(R.id.card_image);
this.requestManager = requestManager;
this.viewHolderListener = viewHolderListener;
itemView.findViewById(R.id.card_view).setOnClickListener(this);
}

void onBind() {
int adapterPosition = getAdapterPosition();
setImage(adapterPosition);
// Set the string value of the image resource as the unique transition name for the view.
image.setTransitionName(String.valueOf(IMAGE_DRAWABLES[adapterPosition]));
}

void setImage(final int adapterPosition) {
// Load the image with Glide to prevent OOM error when the image drawables are very large.
requestManager
.load(IMAGE_DRAWABLES[adapterPosition])
.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model,
Target<Drawable> target, boolean isFirstResource) {
viewHolderListener.onLoadCompleted(image, adapterPosition);
return false;
}

@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable>
target, DataSource dataSource, boolean isFirstResource) {
viewHolderListener.onLoadCompleted(image, adapterPosition);
return false;
}
})
.into(image);
}

@Override
public void onClick(View view) {
// Let the listener start the ImagePagerFragment.
viewHolderListener.onItemClicked(view, getAdapterPosition());
}
}

}

现在也为 viewpager 创建适配器,它将在单击 recyclerView 中的项目后在 viewpager 中显示图像:

public class ImagePagerAdapter extends FragmentStatePagerAdapter {

public ImagePagerAdapter(Fragment fragment) {
// Note: Initialize with the child fragment manager.
super(fragment.getChildFragmentManager());
}

@Override
public int getCount() {
return IMAGE_DRAWABLES.length;
}

@Override
public Fragment getItem(int position) {
return ImageFragment.newInstance(IMAGE_DRAWABLES[position]);
}
}

首先为“ImagePagerFragment”创建 xml 和转换,如下所示:

fragment_image.xml

<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="@string/image_description"
android:scaleType="fitCenter"/>

在res目录下创建transition文件夹:

image_shared_element_transition.xml

<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="375"
android:interpolator="@android:interpolator/fast_out_slow_in"
android:transitionOrdering="together">
<changeClipBounds />
<changeTransform />
<changeBounds />
</transitionSet>

grid_exit_transition.xml

<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="375"
android:interpolator="@android:interpolator/fast_out_slow_in"
android:startDelay="25">
<fade>
<targets android:targetId="@id/card_view" />
</fade>
</transitionSet>

现在创建“ImagePagerFragment”用于在 viewPager 中显示图像

/**
* A fragment for displaying a pager of images.
*/
public class ImagePagerFragment extends Fragment {

private ViewPager viewPager;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
viewPager = (ViewPager) inflater.inflate(R.layout.fragment_pager, container, false);
viewPager.setAdapter(new ImagePagerAdapter(this));
// Set the current position and add a listener that will update the selection coordinator when
// paging the images.
viewPager.setCurrentItem(MainActivity.currentPosition);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
MainActivity.currentPosition = position;
}
});

prepareSharedElementTransition();

// Avoid a postponeEnterTransition on orientation change, and postpone only of first creation.
if (savedInstanceState == null) {
postponeEnterTransition();
}

return viewPager;
}

/**
* Prepares the shared element transition from and back to the grid fragment.
*/
private void prepareSharedElementTransition() {
Transition transition =
TransitionInflater.from(getContext())
.inflateTransition(R.transition.image_shared_element_transition);
setSharedElementEnterTransition(transition);

// A similar mapping is set at the GridFragment with a setExitSharedElementCallback.
setEnterSharedElementCallback(
new SharedElementCallback() {
@Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
// Locate the image view at the primary fragment (the ImageFragment that is currently
// visible). To locate the fragment, call instantiateItem with the selection position.
// At this stage, the method will simply return the fragment at the position and will
// not create a new one.
Fragment currentFragment = (Fragment) viewPager.getAdapter()
.instantiateItem(viewPager, MainActivity.currentPosition);
View view = currentFragment.getView();
if (view == null) {
return;
}

// Map the first shared element name to the child ImageView.
sharedElements.put(names.get(0), view.findViewById(R.id.image));
}
});
}
}

现在创建将作为 viewpager 项目打开的“ImageFragment”:

public class ImageFragment extends Fragment {

private static final String KEY_IMAGE_RES = "com.key.imageRes";

public static ImageFragment newInstance(@DrawableRes int drawableRes) {
ImageFragment fragment = new ImageFragment();
Bundle argument = new Bundle();
argument.putInt(KEY_IMAGE_RES, drawableRes);
fragment.setArguments(argument);
return fragment;
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_image, container, false);

Bundle arguments = getArguments();
@DrawableRes int imageRes = arguments.getInt(KEY_IMAGE_RES);

// Just like we do when binding views at the grid, we set the transition name to be the string
// value of the image res.
view.findViewById(R.id.image).setTransitionName(String.valueOf(imageRes));

// Load the image with Glide to prevent OOM error when the image drawables are very large.
Glide.with(this)
.load(imageRes)
.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable>
target, boolean isFirstResource) {
// The postponeEnterTransition is called on the parent ImagePagerFragment, so the
// startPostponedEnterTransition() should also be called on it to get the transition
// going in case of a failure.
getParentFragment().startPostponedEnterTransition();
return false;
}

@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable>
target, DataSource dataSource, boolean isFirstResource) {
// The postponeEnterTransition is called on the parent ImagePagerFragment, so the
// startPostponedEnterTransition() should also be called on it to get the transition
// going when the image is ready.
getParentFragment().startPostponedEnterTransition();
return false;
}
})
.into((ImageView) view.findViewById(R.id.image));
return view;
}
}

全部搞定!您可以运行此代码并获得我在上面的 gif 中取得的成果。在这里你可以看到我没有添加或删除 fragment 。只需用共享的过渡元素替换当前 fragment 。

Note: In this example i have only take 5 items here. if you want to take extra items and load dynamic urls then you can also do with this.

关于android - 共享元素过渡 imageview 变白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55555359/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com