Search code examples
androidadapter

Change RecycleView item width?


I know there is probably a very simple solution out there, but for the life of me I can't seem to find it. How do I change the width of the RecycleView item? For some reason, it's displaying the first item full width of the parent... It's displaying a lot of white space in between each item.

enter image description here

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/main_wrapper"
        android:background="@color/colorPrimary"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.2"
            android:padding="20dp"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Categories"
                android:textColor="#ffffff"
                android:layout_marginBottom="10dp"/>

            <android.support.v7.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/cats"
                ></android.support.v7.widget.RecyclerView>

        </LinearLayout>
</LinearLayout>

CategoryAdapter:

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {

private ArrayList<Category> categories;

public CategoryAdapter(ArrayList<Category> categories) {
    this.categories = categories;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_cat, parent, false);
    return new ViewHolder(v);
}

@Override public void onBindViewHolder(ViewHolder holder, int position) {
    Category cat = this.categories.get(position);
    holder.text.setText(cat.getText().toString());
}

@Override public int getItemCount() {
    return categories.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    public TextView text;

    public ViewHolder(View itemView) {
        super(itemView);
        text = (TextView) itemView.findViewById(R.id.cat_title);
    }
}

}

single_cat.xml

<TextView
    android:layout_width="100dp"
    android:layout_height="40dp"
    android:text="Cat"
    android:background="@drawable/cat_single_shape"
    android:padding="10dp"
    android:gravity="center"
    android:id="@+id/cat_title"
    android:textSize="13sp"
    android:fontFamily="@font/open_sans_bold"
    android:textColor="@color/colorPrimary"/>

Solution

  • Finally, after 2 days and looking all over the internet, I figured it out myself.

    Make sure your Constraint Layout is wrap_content. This was the issue all along!