android developer
android developer

Reputation: 116332

How to center RecyclerView in the center (and without scrolling) when possible?

This is a short question:

Suppose I have a RecyclerView that has undefined number of items, what should I do to it, so that if there is a small number of items that (all) can fit the screen, they will be centered and the user won't be able to scroll ?

Of course, if there are too many items, that cannot fit the screen, I would like to have the RecyclerView to show them all as normal (from the beginning to how much it can show, and allow to scroll).

To understand what I mean, I think such a thing is possible when using ScrollView (or HorizontalScrollView if in horizontal), together with a LinearLayout that sets the gravity to be centered .

Upvotes: 2

Views: 4395

Answers (2)

android developer
android developer

Reputation: 116332

OK, I think I've found a way:

first, we wait for the RecyclerView to finish its layout process, as I've found about here .

Then, you need to check which child views are shown (available in the LayoutManager that you use), and look at the first and last ones.

If both of them are exactly the same as those that of the total items, it means all needed views are shown, so I can add margins on both sides of the RecyclerView (or padding on its container), according to the space that's left.

Upvotes: 3

空気嫁
空気嫁

Reputation: 186

I found one complicate way to achieve that.

Main concept: set the height of RV dynamicly in code

    RecyclerView rv= (RecyclerView) findViewById(R.id.rv);
    rv.setAdapter(new MySlideUpAdapter());
    rv.setLayoutManager(new LinearLayoutManager(this));
    ViewGroup.LayoutParams layoutParams = rv.getLayoutParams();
    layoutParams.height=100;
    rv.setLayoutParams(layoutParams);

You may need to calculate the RV's height by childcount*childheight to get pricise value. And don't forget to compare the height to the Parent Layout height, make sure RV's height is less than its Parent Layout height.

Here is my Layout

   <RelativeLayout...>
     <android.support.v7.widget.RecyclerView
       android:id="@+id/rv"
       android:layout_centerInParent="true"
       android:layout_width="match_parent"
       <-height will be changed in code, ignore the 50dp-> 
       android:layout_height="50dp">
     </android.support.v7.widget.RecyclerView>
   </RelativeLayout>

enter image description here

Upvotes: 1

Related Questions