Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView items wrap_content width

My Recyclerview is a list of messages.

Each item is a linearlayout with a wrap_content width.

The problem is that when a new item is inserted, the item would take the previous item's width if it's bigger (Which makes it look like it has a big padding)

I tried setRecycable(false) in ViewHolder constructor but that caused some problems and I want to use a different approach.

Any help is appreciated. Thanks

EDIT: Layout:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<include
    android:id="@+id/message_date_layout"
    layout="@layout/time_bubble"/>

<LinearLayout
    android:id="@+id/message_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="4dp"
    android:layout_marginEnd="30dp"
    android:layout_marginLeft="6dp"
    android:layout_marginRight="30dp"
    android:layout_marginStart="6dp"
    android:background="@drawable/background_incoming_chat_bubble"
    android:orientation="vertical"
    android:padding="6dp">
//other views
 </LinearLayout>
</LinearLayout>

CraeteViewHolder

  @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ChatMessagesAdapter.ViewHolder viewHolder;
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = null;
        switch (viewType) {
            case OUTGOING:
                v = inflater.inflate(R.layout.chat_bubble_outgoing, parent, false);
                break;
            case INCOMING:
                v = inflater.inflate(R.layout.chat_bubble_incoming, parent, false);
                break;
        }
        viewHolder = new ChatMessagesAdapter.ViewHolder(v);
        return viewHolder;
    }
like image 388
Roudi Avatar asked May 26 '26 03:05

Roudi


1 Answers

Can you try this in your Adapter

      @Override
      public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            holder.itemView.requestLayout();
      }

maybe this will force the layout to recalculate its dimensions

like image 90
Mohammad Ersan Avatar answered May 28 '26 16:05

Mohammad Ersan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!