简体   繁体   中英

Change Recyclerview row design when swiching between LayoutManger types (Grid - Linear)

I'm trying to learn more about RecyclerView and its implementations, so in this case I need to to design tow item views, one will show when LayoutManager is LinearLayoutManager which in this case will show a vertical List of cards, the second item design will be used when changing LayoutManager to GridLayoutManager type.

my question is how to implement such logic?

I read some answers here, like this about Recyclerview with multiple row design but found nothing about switching between LayoutManager types. and according to this talk we shouldn't play with layout manager in Adapter.

finally I have to mention that I'm new to Android development so I hope my question is clear, and I appreciate any help.

If you wanna change between vertical linear layout and grid (vertical) layout, just use GridLayoutManager and change the column span between 1 (vertical layout) and a value higher than 1 (for grid).

You can use different span values for different layouts using the layout qualified resource folders.

For instance, imagine you want vertical linear in portrait and grid in land:

int spanCount = getResources().getInteger(R.integer.column_count);
return new GridLayoutManager(context, spanCount);

Then create values/integer.xml and values-land/integers.xml where you will define column_count with the different values.

you can create both layout managers and set the right manager to your RecyclerView in the activity and not the adapter according to a certain condition (screen orientation for example):

@Override
protected void onCreate(Bundle savedInstanceState) {
    RecyclerView mRecyclerView
    int numberOfColumns = 3;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout_here);
    LinearLayoutManager mLinearLayoutManager = new  LinearLayoutManager(this,LinearLayoutManager.VERTICAL, false);
    GridLayoutManager mGridLayoutManager = new GridLayoutManager(this,numberOfColumns);
    mRecyclerView = (RecyclerView) findViewById(R.id.your_view_recycler)
    if (condition){
      mRecyclerView.setLayouManager(mLinearLayoutManager)
    } else {
       mRecyclerView.setLayoutManager(mGridLayoutManager)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM