Warm tip: This article is reproduced from stackoverflow.com, please click
android android-recyclerview staggeredgridlayoutmanager

RecyclerView with StaggeredGridLayoutManager : variable number of columns and vertically scrollable

发布于 2020-03-29 20:58:56

I want to show a list of strings, this list has to be vertically scrollable, and for each row a variable number of columns, this column with will depend on the string with. So it will be a grid vertically scrollable. So Graphically I want to achieve this : enter image description here

What I'm getting as a result is a horizontally scrollable list, with 3 rows and many columns, and what I want is the other way around : NOT horizontally scrollable (many columns, depending on the team name) but vertically scrollable.

In order to get this I've added a StaggeredGridLayoutManager to the recycler view with 3 span count (this might be wrong) and StaggeredGridLayoutManager.GAP_HANDLING_NONE to have as many columns as I can.

First question would be is it possible to achieve this with StaggeredGridLayoutManager? If yes how can I fix my problem? Any suggestion or idea is welcome.

Note that the item in the xml has a max width and then it ellipsizes

What I have is the following : item_team.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>

    <variable
        name="title"
        type="String" />

</data>

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/margin_small"
    android:background="@drawable/club_background"
    android:padding="@dimen/margin_general">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:ellipsize="end"
        android:maxWidth="184dp"
        android:gravity="center"
        android:lines="1"
        android:text="@{title}"
        tools:text="Arsenal" />

</RelativeLayout>

TeamAdapter.java :

public class TeamAdapter extends ListAdapter<TeamItem, RecyclerView.ViewHolder> {
private LayoutInflater inflater;
private List<TeamItem> items = new ArrayList<>();

private static final DiffUtil.ItemCallback<TeamItem> ITEM_CALLBACK = new DiffUtil.ItemCallback<TeamItem>() {
    @Override
    public boolean areItemsTheSame(@NonNull TeamItem item1, @NonNull TeamItem item2) {
        return item1.hashCode() == item2.hashCode();
    }

    @Override
    public boolean areContentsTheSame(@NonNull TeamItem item1, @NonNull TeamItem item2) {
        return item1.id.equalsIgnoreCase(item2.id);
    }
};

private static final int VIEW_TYPE_TEAM = 0;

public TeamAdapter(Context context) {
    super(ITEM_CALLBACK);
    inflater = LayoutInflater.from(context);
}

public void setTeams(List<TeamItem> teams) {
    items = teams;
    notifyDataSetChanged();
}

public class TeamViewHolder extends RecyclerView.ViewHolder {

    private final ItemTeamBinding binding;

    TeamViewHolder(ItemTeamBinding binding) {
        super(binding.getRoot());
        this.binding = binding;
    }

    public void bind(TeamItem team) {
        binding.setTitle(team.name);
        binding.executePendingBindings();
    }
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    switch (viewType) {
        case VIEW_TYPE_TEAM:
            ItemTeamBinding itemTeamBinding = DataBindingUtil.inflate(inflater, R.layout.item_team, parent, false);
            return new TeamItemViewHolder(itemTeamBinding);
    }

    throw new RuntimeException("There are invalid view types in TeamAdapter!");
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int position) {
    switch (viewHolder.getItemViewType()) {
        case VIEW_TYPE_TEAM:
            ((TeamItemViewHolder) viewHolder).bind(items.get(position));
            break;
    }
}

@Override
public int getItemCount() {
    if (items != null && !items.isEmpty()) {
        return items.size();
    }

    return super.getItemCount();
}

@Override
public int getItemViewType(int position) {
    if (items != null && !items.isEmpty()) {
        return VIEW_TYPE_TEAM;
    }

    return super.getItemViewType(position);
  }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>

    <variable
        name="activity"
        type="com.ziniestro.base.activity.MainActivity" />

</data>

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/tlbMain"
            android:layout_width="match_parent"
            android:layout_height="?android:actionBarSize"
            app:contentInsetLeft="0dp"
            app:contentInsetStart="0dp"
            app:navigationIcon="@null">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/margin_large"
                android:paddingTop="@dimen/margin_large"
                android:paddingBottom="@dimen/margin_large"
                android:text="@string/main_title" />

        </androidx.appcompat.widget.Toolbar>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/margin_medium"
            android:layout_marginTop="@dimen/margin_small"
            android:layout_marginEnd="@dimen/margin_medium"
            android:layout_marginBottom="@dimen/margin_xlarge"
            android:background="@drawable/round_border_station_preference"
            android:orientation="vertical">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/imgMain"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentTop="true"
                    android:layout_marginStart="@dimen/margin_medium"
                    android:layout_marginTop="@dimen/margin_medium"
                    android:layout_marginBottom="@dimen/margin_xlarge"
                    android:src="@drawable/ic_title" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_marginStart="@dimen/margin_large"
                    android:layout_marginTop="@dimen/margin_xlarge"
                    android:layout_toEndOf="@+id/imgMain"
                    android:gravity="center|start"
                    android:text="@string/main_title" />

            </RelativeLayout>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rcyMain"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layoutAnimation="@anim/layout_anim_scale"
                tools:listitem="@layout/item_team" />

        </LinearLayout>

    </LinearLayout>

</androidx.core.widget.NestedScrollView>

MainActivity.java

public class MainActivity extends AppCompatActivity {

private ActivityMainBinding binding;
public TeamAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    binding.setActivity(this);
    binding.tlbMain.setTitle(Constants.EMPTY_STRING);

    final Drawable backIcon = ContextCompat.getDrawable(this, R.drawable.ic_arrow_back);
    backIcon.setColorFilter(ContextCompat.getColor(this, R.color.secondary) + 0xFF000000, PorterDuff.Mode.SRC_ATOP);
    binding.tlbMain.setNavigationIcon(backIcon);

    setSupportActionBar(binding.tlbMain);

    adapter = new TeamAdapter(this);

    if(MainApplication.getInstance().teamFeed.items !=null && !MainApplication.getInstance().teamFeed.items.isEmpty()) {
        adapter.setTeams(MainApplication.getInstance().teamFeed.items);
        StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        binding.rcyMain.setLayoutManager(gridLayoutManager);

        binding.rcyMain.setHasFixedSize(true);
        binding.rcyMain.setAdapter(adapter);
        binding.rcyMain.setNestedScrollingEnabled(false);
    }
}
}
Questioner
ziniestro
Viewed
20
Andrew 2020-01-31 19:34

I think that you want is the FlexboxLayoutManager https://github.com/google/flexbox-layout#flexboxlayoutmanager-within-recyclerview With the Wrap option in a Vertical Recyclerview.

The "Cells" that contain the Strings you want can vary in size and if it cannot fit a Cell on to the line it wraps it to the next line.