RecyclerView,是在v7包加入的,一个灵活的view可以展示巨大的数据集,类似于listview的viewholder复用已经优化好了。
语言是苍白的,代码是最生动的叙说:
布局:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ui.main.MainActivity" android:padding="12dp" android:orientation="vertical"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler" android:layout_width="match_parent" android:layout_height="match_parent" android:overScrollMode="never" android:clipToPadding="false"/> <ProgressBar android:id="@+id/progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:visibility="gone" /> </FrameLayout>
adapter:
package com.escorps.retrodagger.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.escorps.retrodagger.R; import com.escorps.retrodagger.models.PetModel; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{ private List<PetModel> items; public void setItems(List<PetModel> items){ this.items = items; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { final PetModel item = items.get(position); holder.textName.setText(item.getName()); holder.itemView.setTag(item); } @Override public int getItemCount() { return items.size(); } protected static class ViewHolder extends RecyclerView.ViewHolder { @InjectView(R.id.textName) TextView textName; public ViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); } } }
注意在使用adapter之前: recyclerView.setLayoutManager(new GridLayoutManager(this, 1));