RecyclerView CardLayout images getting smaller in size after each refresh

RecyclerView CardLayout images getting smaller in size after each refresh

glide resize image aspect ratio
glide android
glide image stretched
android-glide crop image
glide image zoom android
resize image in android programmatically
compress image using glide android
how to set aspect ratio of image in android

I'm using RecyclerView and CardLayout on a TabLayout with 5 tabs, each represented as a fragment. Whenever I click on a tab, i first check if the fragment is visible. If true, I execute my UI code which involves invoking a REST service to fetch data from a db which is then populated to the RecyclerView by a custom adapter. I temporarily cache the data in an ArrayList so that frequent attempts to the fragment wont need another REST request. My problem is whenever I navigate to a certain tab more than once, the layout gets smaller and smaller after each attempt. Below are my Fragment, Adapter and Adapter Layout.

public class BeerFragment extends Fragment {
    private RecyclerView recyclerView;
    ProgressDialog pd;
    private View rootView;
    private static final String TAG = BeerFragment.class.getSimpleName();
    public static boolean isLoadedBeer = false;
    public boolean instantiated = false;
    public BeerFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        rootView  = inflater.inflate(R.layout.activity_main2, container, false);
        initViews();
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && MaintainState.isLoadedBeer) {
            initViews();
        } else if (isVisibleToUser && !MaintainState.isLoadedBeer) {
        } else if (!isVisibleToUser && MaintainState.isLoadedBeer){
        } else if (!isVisibleToUser && !MaintainState.isLoadedBeer){
            MaintainState.isLoadedBeer = true;
        }
    }

    private void initViews(){
        pd = new ProgressDialog(getActivity());
        pd.setMessage("Fetching Beer...");
        pd.setCancelable(false);
        pd.show();
        Log.d("snopww4","noppww");
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }

        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        ArrayList albumList = new ArrayList<>();
        GalleryAdapter  adapter = new GalleryAdapter(getActivity(), albumList,2);
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, GridSpacingItemDecoration.dpToPx(getActivity(), 10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        if (!isLoadedBeer) {
            Log.d("lklk","lklk");
        String drink = FilterFragment.sorted;
        if (drink.equals("empty")){
            loadBeer("beer");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("lager")){
            loadBeer("lager");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("stout")){
            loadBeer("stout");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("malt")){
            loadBeer("malt");
            FilterFragment.sorted = "empty";
        } else {
            pd.hide();
        }
    } else {
        recyclerView.setAdapter(new GalleryAdapter(getActivity(), MaintainState.getItemsBeer(), 1));
        recyclerView.smoothScrollToPosition(0);
        pd.hide();
    }
    }

    private void loadBeer(final String item){
        try{
            Client Client = new Client();
            Service apiService = Client.getClient().create(Service.class);
            Call<GalleryResponse> call = apiService.getBeer(item);
            call.enqueue(new Callback<GalleryResponse>() {
                @Override
                public void onResponse(Call<GalleryResponse> call, Response<GalleryResponse> response) {
                    List<Gallery> items = response.body().getBeer();
                    recyclerView.setAdapter(new GalleryAdapter(getActivity(), items, 2));
                    recyclerView.smoothScrollToPosition(0);
                    MaintainState.setItemsBeer(items);
                    isLoadedBeer = true;
                    pd.hide();
                }

                @Override
                public void onFailure(Call<GalleryResponse> call, Throwable t) {
                    pd.hide();

                }
            });
        }catch (Exception e){
        }
    }
}



public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {

    private Context mContext;
    private List<Gallery> albumList;
    private int tabPosition;
    private LocalStore localStore;
    private static final String TAG = GalleryAdapter.class.getSimpleName();

    public GalleryAdapter(Context mContext, List<Gallery> albumList, int tabPosition) {
        Log.i(TAG, "INIT GalleryAdapter");
        this.mContext = mContext;
        this.albumList = albumList;
        this.tabPosition = tabPosition;
        localStore = new LocalStore(mContext);
    }


    @Override
    public GalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.album_card2, viewGroup, false);
        CardView cardView = (CardView) view.findViewById(R.id.card_view);
        cardView.setMaxCardElevation(GridSpacingItemDecoration.dpToPx(mContext, 10));
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final GalleryAdapter.MyViewHolder viewHolder, int i) {
        viewHolder.title.setText(albumList.get(i).getName());
        viewHolder.title.setTypeface(Display.displayTypefaceCabin(mContext, 1), Typeface.BOLD);
        viewHolder.count.setText("Ksh "+albumList.get(i).getPrice());
        viewHolder.count.setTypeface(Display.displayTypefaceWalkWay(mContext, 1), Typeface.BOLD);
        viewHolder.tag.setTypeface(Display.displayTypefaceOpenSansCondensed(mContext, 1), Typeface.BOLD);

        Glide.with(mContext).
                load(albumList.get(i).getThumbnail()).
                placeholder(R.drawable.placeholder).
                error(R.drawable.placeholder).
                fitCenter().
                into(viewHolder.thumbnail);
    }

    @Override
    public int getItemCount() {
        return albumList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, count, tag;
        public ImageView thumbnail, favourite;

        public MyViewHolder(final View view) {
            super(view);
            tag = (TextView) view.findViewById(R.id.tag);
            title = (TextView) view.findViewById(R.id.title);
            count = (TextView) view.findViewById(R.id.count);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            favourite = (ImageView) view.findViewById(R.id.favourite);

            thumbnail.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                }
            });
        }
    }
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:background="#f2f5f7"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_marginLeft="-10dp"
        card_view:cardCornerRadius="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:background="@drawable/image_view_drop_shadow"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/tag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="3dp"
                android:paddingBottom="3dp"
                android:text="hello"
                android:textColor="@color/white"
                android:textSize="12dp"/>

            <ImageView
                android:id="@+id/favourite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="5dp"
                android:layout_alignParentRight="true"/>

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_width="match_parent"
                android:layout_height="220dp"
                android:clickable="true"
                android:scaleType="fitXY" />

            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/thumbnail"
                android:gravity="center"
                android:textColor="#000000"
                android:paddingBottom="5dp"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/count"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/title"
                android:gravity="center"
                android:paddingBottom="15dp"
                android:textSize="14sp" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

I encountered similar problem with images getting smaller on recyclerview refreshes. I used Glide and looked for possible issues. Glide documentation states:

Sometimes when using RecyclerView, a View may be re-used and retain the size from a previous position that will be changed for the current position. To handle those cases, you can create a new [ViewTarget and pass in true for waitForLayout]:

@Override
public void onBindViewHolder(VH holder, int position) {
  Glide.with(fragment)
    .load(urls.get(position))
    .into(new DrawableImageViewTarget(holder.imageView, /*waitForLayout=*/ true));

In Glide 4.6.1 DrawableImageViewTarget(ImageView, waitForLayout) is deprecated so I ended with:

GlideApp.with(context)
                        .load(imageUrl)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(new ViewTarget<ImageView, Drawable>(holder.imageView) {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                holder.imageView.setImageDrawable(resource);
                            }
                        }
                        .waitForLayout());

It helped me to resolve issue.

Image size changed after being reloaded · Issue #1591 · bumptech , Image size changed after being reloaded #1591. Closed failed on all devices I have, such as Nexus 5 6.0.1 images in recyclerview become smaller and smaller as i pull up the list #1506 Reload to refresh your session. 1 get current running thread executor service clojure Feb 14 '17 0 ViewPager ScrollView not working May 31 '17 0 RecyclerView CardLayout images getting smaller in size after each refresh Dec 4 '17


Its because of initViews(). You are calling two times first is from onCreate and second from setUserVisibleHint.

RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(mLayoutManager);

This will crating your size smaller after each refresh.

Mastering Complex Lists with the Android RecyclerView, RecyclerView CardLayout images getting smaller in size after each refresh I'm using RecyclerView and CardLayout on a TabLayout with 5 tabs, each  RecyclerView can still change its size based on other factors (e.g. its parent's size) but this size calculation cannot depend on the size of its children or contents of its adapter (except the number of items in the adapter). If your use of RecyclerView falls into this category, set this to true.


Here's a wild guess.

What I think is happening is that your fragment calls initViews() multiple times, and every time it is called, you are adding a decoration that adds some sort of spacing, which makes less space for your actual views.

Very quick test, removing the below line and see if the problem goes away.

 recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, GridSpacingItemDecoration.dpToPx(getActivity(), 10), true));

If it does, debug your initView() methods to see if it's called more than you need, or maybe split the initView() method into two parts, one for one time things Decorator, Animator... etc. and another one that updates data in view.

Getting Started With RecyclerView and CardView on Android, Valdio Veliu looks at the RecyclerView in Android, perfect for If you are getting started with Android development or are already an The idea is simple: to present a large collection of data using a small Sync Gradle and you are all set. Create a file named row_layout.xml and add the following to it: Android Custom Grid RecyclerView with Images and Text March 8, 2016 Raj Amal Android Development 37 Comments In our previous RecyclerView tutorials we learned about loading image to RecyclerView list.


Android working with Card View and Recycler View, At the time of writing, less than 2% of Android devices run Android the following code to your layout XML as shown in the following snippet: If you are sure that the size of the RecyclerView won't be changing, We specify the layout that each item of the RecyclerView should use. Update me weekly. I have a gallery of images using recyclerview with different size of images. At first draw, it will load and fade-in image (as it should be) but when I scroll back to the top the image is displayed like first time and it takes a little time to be displayed and fade-in (I want it to be instantly there and not fade-in)


Dynamically Loading Recycler View Images in Android, Android tutorial about integrating CardView with RecyclerView. music app that displays music albums with a cover image and title. first of all thank you very much for a simple explanation of cardlayout, but return albumList.size(); } Can you please help i get error on this line after applying clicklistener. For instance, I have a counter on each view that is populated, and as people vote on that topic, I want the counter to increase: My idea is to set a tag to each view that is populated in the RecyclerView , find a way to get the current views that are on the screen, and then update those views dynamically.


Questions for tag cardlayout, When Android apps display thumbnail images in recycler views, images are retrieved separately afterward. Learn how Each record contains a photo ID, album ID, and title, as well as URLs for both thumbnail and full-size images; for example: into a list of Photo objects and the recycler view is refreshed. Android Recycler Listview with Circular Image Hi welcome back , in this tutorial I am going to talk about RecyclerView in Android . Android RecyclerView is more advanced version of ListView with improved performance and other benefits. To know details of Recyclerview you must follow the documentation .