Good day.
How to make a live view of CardView in RecyclerView ?
The user can create a card with an image and without. The image in the template does not exceed 120dp .
If the user adds an image, there is no problem. If it does not add, it creates an empty space of 120dp , which, according to the idea, should not be, only text and description.
If you make the height of the image wrap_content , then the card may be full screen, which is unacceptable.

Template:

  <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/item_image" android:layout_width="match_parent" android:layout_height="120dp" android:scaleType="centerCrop" android:src="@drawable/forest" /> <TextView android:id="@+id/item_title" android:layout_width="250dp" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="30dp" android:text="TextView" /> <TextView android:id="@+id/item_description" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:text="TextView" /> </LinearLayout> </android.support.v7.widget.CardView> 


It should be:
enter image description here

    2 answers 2

    If the user creates CardView without an image, then it is necessary to set the visibility of the ImageView to be View.GONE , and if with the image, then View.VISIBLE .

     @Override public void onBindViewHolder(ViewHolder holder, int position){ ... Item item = items.get(position); holder.imageView.setVisibility(item.getImage() == null ? View.GONE : View.VISIBLE); } 

    And the fact that the card can be on the whole screen is a normal behavior, since RecyclerView re-uses the View , but does not recreate it . That is why it is important to handle both variants of the item.getImage() == null condition, since if we process only that moment when there is no picture, RecyclerView can reuse the card with which ImageView hidden, and even though there is a picture in item'e , it will not be shown, since we have not processed the corresponding moment of the condition.

    • Wow, thanks a lot! :) - Slyly

    You can do this:

     // в адаптере проверять нужно ли показывать картинку imageView.setVisibility(item.hasImage() ? View.VISIBLE : View.GONE); 

    Instead of item.hasImage (), substitute the desired boolean value that determines whether the image is for this CardView or not.