Can Android RecyclerView contain Non Container Views instead of View Container

41 views Asked by At

So basically RecyclerView inflates item View wrapped in (Layout Holder). E.g. For a RecyclerView the items that are inflated in the adapter are like :

list_item.xml contains below code:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
    <Button
        android:id="@+id/option"
        android:layout_height="50dp"
        android:layout_width="match_parent"
        android:text="TESTING"/>
</LinearLayout>

Can it not be like below code?

<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:id="@+id/option"
        android:layout_height="50dp"
        android:layout_width="match_parent"
        android:text="TESTING"/>
</merge>

Because RecyclerView is Container View that can hold simple non-container views and container views (like LinearLayout etc.) Container Views - View which can hold simple views (TextView, button etc.) as well as container Views (like LinearLayout etc.). Simple Views - can not hold any other view within it.

And during inflation in the adapter, we attach it root:-

final View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.dialog_locker_open_item, parent, true);

The above give exception.

It should have merged but was getting expectation during inflation.

1

There are 1 answers

0
Pawel On

Each ViewHolder needs to contain one root view (constructor argument of ViewHolder) so RecyclerView can detach and recycle it when needed.

It's not designed to keep track of "multiple non-container views" per item (which would happen if you were inflating with <merge> tag).

Also inflate with attachToParent=true is conceptually wrong and will always fail as RecyclerView.Adapter is not the component responsible for laying out the views in RecyclerView (this is the duty of RecyclerView.LayoutManager).