-2

I want to set two RecyclerViews on a screen of equal height to cover the screen equally, the problem is, if I use height as wrap_content views don't expand equally, and if I fix their heights or give them layout_weight, than there will be white space if one of the list is empty.

I want the lists don't occupy space if these one of them is empty, and if there is data in both lists, than they cover equal space on the screen.

Asad
  • 1,241
  • 3
  • 19
  • 32

2 Answers2

3

You can't do this only in XML. You'll need a little Java. You were on the right track with the layout weights.

Skeleton XML:

<LinearLayout
    android:orientation="vertical">

    <RecyclerView
        android:id="@+id/recView1"
        android:layout_height="0dp"
        android:layout_weight="1"
    />

    <RecyclerView
        android:id="@+id/recView2"
        android:layout_height="0dp"
        android:layout_weight="1"
    />

</LinearLayout>

The next part needs to be done in Java.

Add a data observer to both adapters, and make sure to override all the methods and have them call onChanged(). Then, inside onChanged(), retrieve the count of the current adapter and set the RecyclerView's visibility appropriately.

Here's an example for the first one:

recView1.getAdapter().registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
    @Override
    public void onChanged() {
        recView1.setVisibility(recView1.getAdapter().getItemCount() > 0 ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount) {
        onChanged();
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
        onChanged();
    }

    @Override
    public void onItemRangeInserted(int positionStart, int itemCount) {
        onChanged();
    }

    @Override
    public void onItemRangeRemoved(int positionStart, int itemCount) {
        onChanged();
    }

    @Override
    public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
        onChanged();
    }
}

In practice, you should probably extract both observers to variables, so that you can unregister them when the containing Activity/Window/whatever is destroyed.

TheWanderer
  • 16,775
  • 6
  • 49
  • 63
  • I extracted the AdapterDataObserver with adapter.registerAdapterDataObserver(mObserver);. Then how do you access the registerAdapterDataObserver's override methods like onChanged()? Would this work "mObserver = new RecyclerView.AdapterDataObserver { ...}" and then add the override methods within? – AJW Nov 14 '21 at 00:54
0

Use below code Hope it will work

int x=this. getResources().getDisplayMetrics().heightPixels*1/2;
recyclerview1.setLayoutParams(new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, x));
recyclerview2.setLayoutParams(new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, x));
nhCoder
  • 451
  • 5
  • 11