效果
图片丑就丑吧,看效果就好了
使用
jitpack对开源分享真是友好啊
Step 1.Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
dependencies {
implementation 'com.github.PMMKing:MultiAdapter:1.1'
}
直接上代码,简单粗暴
RecyclerView rlvTest = findViewById(R.id.rlv_test);
rlvTest.setLayoutManager(new LinearLayoutManager(this));
MultiAdapter<Integer> adapter = new MultiAdapter<Integer>(this).addTypeView(new ITypeView<Integer>() {
@Override
public boolean isForViewType(Integer item, int position) {
return position % 2 == 0;
}
@Override
public BaseViewHolder createViewHolder(Context mContext, ViewGroup parent) {
return new ViewHolderOne(mContext, LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false));
}
}).addTypeView(new ITypeView<Integer>() {
@Override
public boolean isForViewType(Integer item, int position) {
return position % 2 != 0;
}
@Override
public BaseViewHolder createViewHolder(Context mContext, ViewGroup parent) {
return new ViewHolderTwo(mContext, LayoutInflater.from(mContext).inflate(R.layout.item2_layout, parent, false));
}
});
rlvTest.setAdapter(adapter);
adapter.setOnItemClickListener(new OnItemClickListener<Integer>() {
@Override
public void onItemClickListener(View view, Integer data, int position) {
Toast.makeText(MainActivity.this, "onClick position is " + position + " data is " + data, Toast.LENGTH_SHORT).show();
}
});
adapter.setOnLongItemClickListener(new OnItemLongClickListener<Integer>() {
@Override
public boolean onItemLongClickListener(View view, Integer data, int position) {
Toast.makeText(MainActivity.this, "onLongClick position is " + position + " data is " + data, Toast.LENGTH_SHORT).show();
return true;
}
});
ArrayList<Integer> list = new ArrayList<>();
Random rand = new Random();
while (true) {
list.add(rand.nextInt());
if (list.size() > 30) {
break;
}
}
adapter.setData(list);
添加点击和长按事件,每多一个布局在adapter后面添加一个addTypeView() 方法,方法里面实现一个ITypeView的实例,复写ITypeView的两个方法,第一个判断当前item要显示那个布局文件,第二个返回一个ViewHolder。
ViewHolder继承BaseViewHolder
public class ViewHolderOne extends BaseViewHolder<Integer> {
private final TextView tvItem;
public ViewHolderOne(Context context, View itemView) {
super(context, itemView);
tvItem = itemView.findViewById(R.id.tv_item);
}
@Override
public void onBindViewHolder(BaseViewHolder holder, Integer data, int position) {
tvItem.setText("布局1的item的position是:" + position + " data是:" + data);
}
}