Dynamically change the number of columns of a GridLayoutManager

后端 未结 3 1968
粉色の甜心
粉色の甜心 2021-02-07 04:06

I am actually using a GridLayoutManager with two columns in my app and I would like to have one column depending on the view type used.

Here is the code I have in the me

相关标签:
3条回答
  • 2021-02-07 04:41

    i was use an checkBox for changing my Layout manager columns. you should use this to change GridLayoutManager columns . here is code :

     checkBox = findViewById(R.id.change_manager);
    
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checkBox.isChecked()) {
                    layoutManager.setSpanCount(2);
                    isLayoutChange = true;
                } else {
                    isLayoutChange = false;
                    layoutManager.setSpanCount(3);
                }
            }
        });
    

    and boolean for checking layoutManager Changes in onResume() , onRestart() and onPause() method. use it like this :

      if (isLayoutChange) {
            layoutManager.setSpanCount(2);
        } else {
            layoutManager.setSpanCount(3);
        }
    
    0 讨论(0)
  • 2021-02-07 04:42
    mGridLayoutManager = new GridLayoutManager(mContext, 2);
    mGridLayoutManager.setSpanSizeLookup(onSpanSizeLookup);    
    
    /**
     * Helper class to set span size for grid items based on orientation and device type
     */
    GridLayoutManager.SpanSizeLookup onSpanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            return mHomeListAdapter.getItemViewType(position) == TYPE_PREMIUM ? 2 : 1;
        }
    };
    
    0 讨论(0)
  • 2021-02-07 04:55

    If I understand your question, you would like to let premium-type Views span 2 columns instead of 1? That's possible by setting a custom SpanSizeLookup with setSpanSizeLookup(SpanSizeLookup).

    0 讨论(0)
提交回复
热议问题