用RecyclerView要导入依赖:
compile 'com.android.support:recyclerview-v7:21.0.0'
CommonAdapter:
public abstract class CommonAdapter extends RecyclerView.Adapter {
private LayoutInflater mLayoutInflater;
private Context mContext;
private List mData;
private int mLayoutId;
public CommonAdapter(Context context,int layoutId,List mData){
this.mContext=context;
this.mLayoutInflater=LayoutInflater.from(context);
this.mData=mData;
this.mLayoutId=layoutId;
}
@Override
public int getItemViewType(int position) {
if (position==13){
return 1;
}else {
return 0;
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType==1){
ViewHolder viewHolder=ViewHolder.get(mContext,R.layout.layout2,parent);
return viewHolder;
}else {
ViewHolder viewHolder=ViewHolder.get(mContext,R.layout.item_layout,parent);
return viewHolder;
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
convert(holder,mData.get(position));
}
public abstract void convert(ViewHolder viewHolder,T item);
@Override
public int getItemCount() {
return mData.size();
}
}
ViewHolder:
public class ViewHolder extends RecyclerView.ViewHolder{
private SparseArray mView;
private View mConvertView;
private Context mContext;
public ViewHolder(Context context, View itemView, ViewGroup parent) {
super(itemView);
this.mContext=context;
mConvertView=itemView;
mView=new SparseArray<>();
}
public static ViewHolder get(Context context,int layLout,ViewGroup parent){
View itemView= LayoutInflater.from(context).inflate(layLout,parent,false);
ViewHolder viewHolder=new ViewHolder(context,itemView,parent);
return viewHolder;
}
public T getView(int viewId){
View view=mView.get(viewId);
if (view==null){
view=mConvertView.findViewById(viewId);
mView.put(viewId,view);
}
return (T)view;
}
public ViewHolder setText(int viewId, String text)
{
TextView tv = getView(viewId);
tv.setText(text);
return this;
}
public ViewHolder setImageResource(int viewId, int resId)
{
ImageView view = getView(viewId);
view.setImageResource(resId);
return this;
}
public ViewHolder setOnClickListener(int viewId,
View.OnClickListener listener)
{
View view = getView(viewId);
view.setOnClickListener(listener);
return this;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List mData=new ArrayList<>();
private CommonAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
for (int i=0;i<30;i++){
mData.add(i+"");
}
recyclerView= (RecyclerView) findViewById(R.id.rv1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter=new CommonAdapter(this,R.layout.item_layout,mData) {
@Override
public void convert(ViewHolder viewHolder, String item) {
TextView tv = viewHolder.getView(R.id.tv);
tv.setText(item);
}
};
recyclerView.setAdapter(adapter);
}
}
main_layout:
item_layout: