1. 程式人生 > >Android設定RecyclerView為GridLayoutManager的時候,根據內容的長度,設定每行顯示不同span

Android設定RecyclerView為GridLayoutManager的時候,根據內容的長度,設定每行顯示不同span

電商專案,搜尋介面,有搜尋歷史和熱詞推薦。item內容都是TextView,但是如果設定每行顯示的item為固定的話,那麼某個詞如果過長的話,當前介面肯定不和諧。下面是處理方法;

 gridLayoutManager = new GridLayoutManager(this, 5);  //設定每行顯示幾個item
//        gridLayoutManager.setSmoothScrollbarEnabled(false);
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
public int getSpanSize(int i) { /** * 重點在這裡,這個getSpanSize方法的返回值其實指的是單個item所佔用的我們設定的每行的item個數*/int stringLenth = data.get(i).length(); if (3 < stringLenth && stringLenth < 6) { return 2; } else if (5 < stringLenth && stringLenth < 9
) { return 3; } else if (8 < stringLenth && stringLenth < 12) { return 4; } else if (12 < stringLenth) { return 5; } else { return 1; } } }); rvHot.setLayoutManager(gridLayoutManager);
hotAdapter = new HotSearcherAdapter(this, R.layout.item_hot_searcher, data); rvHot.setAdapter(hotAdapter);

以上為主要程式碼,意思為如果當前item的文字長度超過了3,小於6,那麼這個item就佔用2個item的大小。以此類推!

mark一下。