Android技术知识Android开发Android开发经验谈

RecyclerView点击item图片,从点击位置,放大到全屏

2018-06-21  本文已影响689人  卖臭豆腐的王致和
转载请注明原创出处,谢谢!

ps:最近要写一个小模块,类似于微信的九宫格,点击一张图片,放大到全屏,再次点击会缩小,而且有一个动画,图片从点击位置开始放大,缩小的时候同样有这样一个缩小动画

效果图.gif

当出现需求时,我一般不会去直接写,我会上网搜了一下其他博客,发现大多数写的很麻烦,有人用弹出Dialog实现,有人在Imageview上面盖了一层视图方法实现,而且代码也很多,上百行,当他们都有一些问题,例如

而我的核心代码,只有3行,就完美的实现了这个效果,而且是在2个Activity实现这个效果,这个效果用到的知识点是Shared Element效果(共享元素效果),有兴趣的同学,可以查阅其他资料。

item的点击事件代码

viewHolder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view.getContext().startActivity(
                        new Intent(view.getContext(), OtherActivity.class),
                        // 注意这里的sharedView
                        // Content,View(动画作用view),String(和XML一样)
                        ActivityOptions.makeSceneTransitionAnimation((Activity) view.getContext(), view, "sharedView").toBundle());
            }
        });

item.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="wrap_content"
    android:orientation="vertical">
    <!--注意这里的sharedView-->
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:transitionName="sharedView" />
</LinearLayout>

OtherActivity的页面布局

<?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">
    <!--注意这里的sharedView-->
    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ic_launcher"
        android:transitionName="sharedView" />
</LinearLayout>

OtherActivity.java(主要实现点击缩小)

findViewById(R.id.imageView2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 注意这里不使用finish
                ActivityCompat.finishAfterTransition(OtherActivity.this);
            }
        });

以上代码,就可以完成我们上面图片的效果,要注意我的注释

上一篇下一篇

猜你喜欢

热点阅读