RecyclerView Example

Package

android.support.v7.widget.RecyclerView

Gradle Dependency

dependencies {
    compile 'com.android.support:recyclerview-v7:24.2.0'
}

Layout

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Activity or Fragment

public class TestActivity extends Activity {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<UserInfo> mData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        mRecyclerView = (RecyclerView)findViewById(R.id.recycler_view);

        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mData = new ArrayList<UserInfo>() ;

        mAdapter = new TestAdapter(mData);
        mRecyclerView.setAdapter(mAdapter);
    }
    ...
}

RecyclerView.Adapter

public class TestAdapter extends RecyclerView.Adapter {
    private List<UserInfo> mData;

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView mTextView;
        public ImageView mImageView;

        public ViewHolder(View itemView) {
            super(itemView);
            mTextView = itemView.findViewById(R.id.user_name);
            mImageView = itemView.findViewById(R.id.user_photo);
        }
    }

    public TestAdapter(List<UserInfo> data) {
        mData = data;
    }

    @Override
    public TestAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {

        View v = LayoutInflater.from(parent.getContext())
                               .inflate(R.layout.user_info, parent, false);

        ViewHolder holder = new ViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.mTextView.setText(mData[position].getUserName());
        holder.mImageView.setImageDrawable(mData[position].getUserPhoto());
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }
}

Demo

Download

RecyclerViewExample.zip