Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering a CardView within a RecyclerView?

Tags:

android

css

I've been playing around with CardViews inside a RecyclerView, but can't seem to get my cards centered.

My cardview.xml:

<android.support.v7.widget.CardView
    android:id="@+id/cardview"
    android:layout_gravity="center_horizontal"
    android:gravity="center"
    android:layout_width="300dp"
    android:layout_height="100dp"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/text"
        android:textAlignment="center"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />

</android.support.v7.widget.CardView>

My activity_main.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal"
    android:gravity="center"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimaryDark"/>

    <!-- A RecyclerView with some commonly used attributes -->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


</LinearLayout>

Image of what my app looks like when I run it:

like image 900
u2fan Avatar asked Dec 19 '22 08:12

u2fan


1 Answers

Okok, I have the same question and I think I have "solved" it. It's really just another hack. The android team at Google really should fix this recycler view and add support for swipe to dismiss.

In onCreateView:

recyclerView.addItemDecoration(new ItemDecoration() {

  @Override
  public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
    int totalWidth = parent.getWidth();
    int maxCardWidth = getResources().getDimensionPixelOffset(R.dimen.card_max_width);
    int sidePadding = (totalWidth - maxCardWidth) / 2;
    sidePadding = Math.max(0, sidePadding);
    outRect.set(sidePadding, 0, sidePadding, padding);
  }
});
like image 80
user2214756 Avatar answered Jan 06 '23 16:01

user2214756