如何实现让RecyclerView有不同尺寸的item

2025-01-03 00:19:21
推荐回答(1个)
回答1:

package tv.lesports.com.myrecyclerview;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

import java.util.ArrayList;

/**
* Created by liuyu8 on 2016/5/3.
*/
public class RecyclerViewActivity extends Activity {
private RecyclerView mRecyclerView;
private HomeAdapter mAdapter;
private ArrayList mDataList;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview_layout);
initData();
mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);
GridLayoutManager manager = new GridLayoutManager(this, 4);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
SearchResultBean bean = mDataList.get(position);
if (bean.getType() == 0) {
return 4;
} else if(bean.getType() == 1){
return 2;
}else{
return 1;
}
}
});
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter = new HomeAdapter(this, mDataList);
mRecyclerView.setAdapter(mAdapter);
}

protected void initData() {
mDataList = new ArrayList();
for (int i = 0; i < 50; i++) {
SearchResultBean bean = new SearchResultBean();
bean.setName(i + "");
if (i == 0) {
bean.setType(0);
} else if (i > 0 && i <= 5) {
bean.setType(1);
} else {
bean.setType(2);
}
mDataList.add(bean);
}
}
}