在全屏android中使用recyclerview幻灯片图像

Posted

技术标签:

【中文标题】在全屏android中使用recyclerview幻灯片图像【英文标题】:Slide image with recyclerview in full screen android 【发布时间】:2020-10-21 18:08:56 【问题描述】:

我已经创建了墙纸应用程序,我正在从 recyclerview 的 firebase 数据库中加载图像。当我点击 recyclerview item(image) 时,该项目的图像 url 发送到下一个活动,然后使用 glide 将该 url 加载到 imageView 中。

现在我想将其更改为 Image-Slider 之类的内容。通过单击 recyclerView 项目,我想全屏显示该图像,并且还想从左或右滑动(下一个或上一个)。但我不知道该怎么做。

这是我的代码。

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        adapter = new FeaturedAdapter(list);
        recyclerView.setAdapter(adapter);

        databaseReference = FirebaseDatabase.getInstance().getReference().child("Wallpaper All");
        Query query = databaseReference.orderByChild("dark").equalTo(true);
        query.addListenerForSingleValueEvent(new ValueEventListener() 
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) 

                list.clear();
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) 

                    FeaturedModel model = dataSnapshot1.getValue(FeaturedModel.class);
                    list.add(model);
                    
                

                adapter.notifyDataSetChanged();

            

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) 

                Log.e("TAG_DATABASE_ERROR", databaseError.getMessage());

            
        );

FeaturedAdapter.java


public class FeaturedAdapter extends RecyclerView.Adapter<FeaturedAdapter.ViewHolder> 

    private List<FeaturedModel> featuredModels;

    public FeaturedAdapter(List<FeaturedModel> featuredModels) 
        this.featuredModels = featuredModels;
    

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_image, parent, false);

        return new ViewHolder(view);
    

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) 

        holder.setData(featuredModels.get(position).getImageLink()
                , position,
                featuredModels.get(position).isPremium());

    

    @Override
    public int getItemCount() 
        return featuredModels.size();
    

    class ViewHolder extends RecyclerView.ViewHolder 

        private ImageView imageView;
        private ImageView premiumImage;

        public ViewHolder(@NonNull View itemView) 
            super(itemView);

            imageView = itemView.findViewById(R.id.imageview);
            premiumImage = itemView.findViewById(R.id.premium);

        

        private void setData(final String url, final int position, boolean premium) 

            Glide.with(itemView.getContext().getApplicationContext()).load(url).into(imageView);

            if (premium) 

                premiumImage.setVisibility(View.VISIBLE);

                itemView.setOnClickListener(new View.OnClickListener() 
                    @Override
                    public void onClick(View v) 
                        Intent setIntent = new Intent(itemView.getContext(), PremiumViewActivity.class);
                        //setIntent.putExtra("title", url);
                        setIntent.putExtra("images", featuredModels.get(getAdapterPosition()).getImageLink());
                        setIntent.putExtra("id", featuredModels.get(position).getId());
                        itemView.getContext().startActivity(setIntent);

                    
                );


             else 

                premiumImage.setVisibility(View.GONE);

                itemView.setOnClickListener(new View.OnClickListener() 
                    @Override
                    public void onClick(View v) 
                        Intent setIntent = new Intent(itemView.getContext(), ViewActivity.class);
                        //setIntent.putExtra("title", url);
                        setIntent.putExtra("images", featuredModels.get(getAdapterPosition()).getImageLink());
                        setIntent.putExtra("id", featuredModels.get(position).getId());
                        itemView.getContext().startActivity(setIntent);

                    
                );

            

        

    



查看活动

Random rnd = new Random();
        int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));

        relativeLayout.setBackgroundColor(color);

        Glide.with(this)
                .load(getIntent().getStringExtra("images"))
                .timeout(6000)
                .listener(new RequestListener<Drawable>() 
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) 
                        relativeLayout.setBackgroundColor(Color.TRANSPARENT);
                        return false;
                    

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) 
                        relativeLayout.setBackgroundColor(Color.TRANSPARENT);
                        return false;
                    
                )
                .into(imageView);
setBackgroundWall.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                setBackgroundImage();

            
        );



 private void setBackgroundImage() 

        Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();

        WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
        try 
            manager.setBitmap(bitmap);
            Toasty.success(getApplicationContext(), "Set Wallpaper Successfully", Toast.LENGTH_SHORT, true).show();

         catch (IOException e) 
            Toasty.warning(this, "Wallpaper not load yet!", Toast.LENGTH_SHORT, true).show();
        
        

    

activity_view.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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_
    android:layout_
    tools:context=".activity.PremiumViewActivity">

    <ImageView
        android:id="@+id/viewImage"
        android:layout_
        android:layout_
        android:adjustViewBounds="true"
        android:contentDescription="@null"
        android:scaleType="centerCrop"
        android:src="#00BCD4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />

    <com.airbnb.lottie.LottieAnimationView
        android:id="@+id/lottieSuccess"
        android:layout_
        android:layout_
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:lottie_fileName="checked.json" />

    <RelativeLayout
        android:id="@+id/wallpaper_layout"
        android:layout_
        android:layout_
        android:padding="16dp"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent">

        <ImageButton
            android:id="@+id/saveImage"
            android:layout_
            android:layout_
            android:layout_alignParentStart="true"
            android:layout_alignParentBottom="true"
            android:layout_marginStart="20dp"
            android:background="@drawable/set_as_wallpaper_btn"
            android:contentDescription="@null"
            android:src="@drawable/save" />

        <Button
            android:id="@+id/setWallpaper"
            android:layout_
            android:layout_
            android:layout_alignParentEnd="true"
            android:layout_alignParentBottom="true"
            android:layout_marginStart="4dp"
            android:layout_marginEnd="8dp"
            android:background="@drawable/set_as_wallpaper_btn"
            android:minWidth="230dp"
            android:text="Set as wallpaper"
            android:textColor="#000"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_
            android:layout_
            android:layout_alignParentTop="true"
            android:layout_alignParentEnd="true"
            android:orientation="horizontal">

            <CheckBox
                android:id="@+id/favoritesBtn_checkbox"
                android:layout_
                android:layout_
                android:layout_margin="6dp"
                android:button="@drawable/favourite_checkbox_selector" />

            <ImageButton
                android:id="@+id/shareBtn"
                android:layout_
                android:layout_
                android:layout_margin="6dp"
                android:background="@drawable/share"
                android:contentDescription="@null" />


        </LinearLayout>


    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/ads_layout"
        android:layout_
        android:layout_
        android:orientation="vertical"
        android:padding="12dp"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent">

        <Button
            android:id="@+id/watch_ads"
            android:layout_
            android:layout_
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            android:background="@drawable/set_as_wallpaper_btn"
            android:drawableStart="@drawable/advertizing"
            android:paddingStart="50dp"
            android:paddingEnd="50dp"
            android:stateListAnimator="@null"
            android:text="Watch Video Ad"
            android:textColor="#000"
            android:textStyle="bold" />

        <RelativeLayout
            android:layout_
            android:layout_
            android:layout_below="@id/watch_ads">

            <Button
                android:id="@+id/unlock_withCoins"
                android:layout_
                android:layout_
                android:layout_marginStart="20dp"
                android:layout_marginTop="15dp"
                android:layout_marginEnd="20dp"
                android:background="@drawable/set_as_wallpaper_btn"
                android:drawableStart="@drawable/diamond"
                android:paddingStart="50dp"
                android:paddingEnd="50dp"
                android:stateListAnimator="@null"
                android:text="Unlock with diamonds"
                android:textColor="#000"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/diamonds_tv"
                android:layout_
                android:layout_
                android:layout_marginTop="50dp"
                android:gravity="center"
                android:text="Total Diamonds: 0"
                android:textSize="10sp"
                android:textStyle="bold" />

        </RelativeLayout>


    </RelativeLayout>


</androidx.constraintlayout.widget.ConstraintLayout>

custom_image.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"
    android:layout_
    android:layout_>

    <androidx.cardview.widget.CardView
        android:layout_
        android:layout_
        android:layout_centerHorizontal="true"
        android:background="#fff"
        app:cardCornerRadius="10dp"
        app:cardUseCompatPadding="true">

        <RelativeLayout
            android:layout_
            android:layout_>

            <ImageView
                android:id="@+id/imageview"
                android:layout_
                android:layout_
                android:contentDescription="@null"
                android:scaleType="centerCrop"
                android:src="@color/colorPrimary" />

            <ImageView
                android:id="@+id/premium"
                android:contentDescription="@null"
                android:layout_
                android:layout_
                android:layout_alignParentTop="true"
                android:layout_alignParentEnd="true"
                android:layout_margin="10dp"
                app:srcCompat="@drawable/diamond" />

        </RelativeLayout>


    </androidx.cardview.widget.CardView>

</RelativeLayout>
Structure

MainActivity
    |
    | //Click button to open
    |
FragActivity
    |
    | //FrameLayout
    |
 Fragment
    |
    | //here is the recyclerView
    | //Open new Activity to view image 
    
ViewActivity

Screen Recording

【问题讨论】:

我想你正在寻找这个 Sample 。如果你正在寻找这个,你应该参考 ViewPager。 @Ramesh 能否提供库链接或示例代码 ViewPager 没有单独的库。请通过此文档developer.android.com/reference/androidx/viewpager/widget/… 您是否尝试过使用视图寻呼机?此外,如果您只对回收站视图感到满意,您可以尝试使用水平方向的线性布局。 不,我正在使用GridLayoutManager 【参考方案1】:

这可以通过在Android中使用ViewPagerViewPager2来解决

首先创建一个适配器

ImageSwiperAdapter2.java

public class ImageSwiperAdapter2 extends RecyclerView.Adapter<ImageSwiperAdapter2.ImageSwiper> 

    private List<FeaturedModel> list;
    private Context context;

    public ImageSwiperAdapter2(List<FeaturedModel> list, Context context) 
        this.list = list;
        this.context = context;
    

    @NonNull
    @Override
    public ImageSwiper onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.slidingimages,
                parent, false);

        return new ImageSwiper(view);
    

    @Override
    public void onBindViewHolder(@NonNull final ImageSwiper holder, int position) 

        Random rnd = new Random();
        int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        holder.relativeLayout.setBackgroundColor(color);

        Glide.with(context.getApplicationContext())
                .load(list.get(position).getImageLink())
                .listener(new RequestListener<Drawable>() 
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) 
                        holder.relativeLayout.setBackgroundColor(Color.TRANSPARENT);
                        return false;
                    

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) 
                        holder.relativeLayout.setBackgroundColor(Color.TRANSPARENT);

                        return false;
                    
                )
                .into(holder.imageView);


    

    @Override
    public int getItemCount() 
        return list.size();
    

    class ImageSwiper extends RecyclerView.ViewHolder 


        private ImageView imageView;
        

        public ImageSwiper(@NonNull View itemView) 
            super(itemView);

            imageView = itemView.findViewById(R.id.imageView);
          

        


    

在 ViewActivity/SwiperActivity.java 中

public class SwiperActivity extends AppCompatActivity 

    private ViewPager2 viewPager;
    private List<FeaturedModel> list;
    private ImageSwiperAdapter2 adapter2;


    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_swiper);

        viewPager = findViewById(R.id.view_pager);
        
        final int pos = getIntent().getIntExtra("pos", 0);

        Singleton singleton = Singleton.getInstance();

        list = new ArrayList<>();
        list = singleton.getListSin();

        adapter2 = new ImageSwiperAdapter2(list, this);

        viewPager.setAdapter(adapter2);
        viewPager.setCurrentItem(pos);

        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() 
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) 
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            

            @Override
            public void onPageSelected(int position) 
                super.onPageSelected(position);

                Toast.makeText(SwiperActivity.this, "Selected: " + position, Toast.LENGTH_SHORT).show();

            

            @Override
            public void onPageScrollStateChanged(int state) 
                super.onPageScrollStateChanged(state);
            
        );

    


您可以通过listFeaturedAdapter 中的单击项目位置。

在您的 FeaturedAdapter's setData 方法中

private void setData(final String url, final int position, boolean premium) 
          Glide.with(itemView.getContext().getApplicationContext()).load(url).into(imageView);

            final Singleton a = Singleton.getInstance();
            a.setListSin(featuredModels);

            if (premium) 

                premiumImage.setVisibility(View.VISIBLE);

                itemView.setOnClickListener(new View.OnClickListener() 
                    @Override
                    public void onClick(View v) 

                        Intent setIntent = new Intent(itemView.getContext(), SwiperActivity.class);
                        
                        setIntent.putExtra("pos", position);
                        itemView.getContext().startActivity(setIntent);
                        CustomIntent.customType(itemView.getContext(), "fadein-to-fadeout");



                    
                );


             else 

                premiumImage.setVisibility(View.GONE);

                itemView.setOnClickListener(new View.OnClickListener() 
                    @Override
                    public void onClick(View v) 
                        
                        Intent setIntent = new Intent(itemView.getContext(), SwiperActivity.class);
                        setIntent.putExtra("pos", position);
                        itemView.getContext().startActivity(setIntent);
                        CustomIntent.customType(itemView.getContext(), "fadein-to-fadeout");

                    
                );

            

        

slidingimages.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_
    android:layout_>

    <ImageView
        android:id="@+id/imageView"
        android:layout_
        android:layout_
        android:adjustViewBounds="true"
        android:contentDescription="@null"
        android:scaleType="centerCrop" />

    
</RelativeLayout>

activity_swiper.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_
    android:layout_
    tools:context=".SwiperActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:orientation="horizontal"
        android:id="@+id/view_pager"
        android:layoutDirection="inherit"
        android:layout_
        android:layout_ />

</RelativeLayout>
    

【讨论】:

【参考方案2】:

由于 ViewActivity 必须显示所有图像(滑动时),它必须包含带有一组图像 url 的适配器。 在 ViewActivity 中使用 RecyclerView 并附加适配器,而不是使用 ImageView。在您的代码中,执行以下操作以使回收器视图水平并添加幻灯片功能。

    recyclerView = view.findViewById(R.id.recycler_view);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));
    SnapHelper snapHelper = new PagerSnapHelper();
    snapHelper.attachToRecyclerView(recyclerView);

【讨论】:

如果可能,请添加 ViewActivity xml 代码,以便我可以编辑我的答案以适应您的问题 我正在重新创建它,很快就会回答 使用 ViewpPager,这是您最好的选择。【参考方案3】:

几天前,我一直在寻找类似的要求来显示可滑动的图像视图。 这种情况可以在Android中使用ViewPager来解决。 您可以使用以下教程使用ViewPager 构建此类幻灯片图像视图

Java 资源

    Blog Tutorial Video Tutorial

Kotlin 资源

    Video Tutorial

【讨论】:

始终欢迎提供指向潜在解决方案的链接,但请在链接周围添加上下文,以便您的其他用户了解它是什么以及为什么存在。始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。欲了解更多信息,请查看this

以上是关于在全屏android中使用recyclerview幻灯片图像的主要内容,如果未能解决你的问题,请参考以下文章

状态栏在全屏对话框片段android中将其颜色更改为黑色

当视频视图处于全屏状态时,RecyclerView 被重新创建

如何在全屏图像上放置评论?

在全屏模式演示样式中使用 segue 时如何仍然显示导航栏?

在全屏启动器应用程序来自后台后,Android NFC 读取失败

全屏 RecyclerView 图像滑块