RecyclerView is new in Android 5.0 (Lollipop).
add compile 'com.android.support:recyclerview-v7:21.0.0' in build.gradle file
This sample code is in GitHub.
To use with support library
add compile 'com.android.support:recyclerview-v7:21.0.0' in build.gradle file
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.0' compile 'com.android.support:recyclerview-v7:21.0.0' }and import
import android.support.v7.widget.RecyclerView;
Get from layout xml
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycle_list);
Plug in LayoutManager
recyclerView.setLayoutManager(layoutManager);
Create Adapter
NameRecyclerAdapter mAdapter; ... mAdapter = new NameRecyclerAdapter();
Plug in Adapter
recyclerView.setAdapter(mAdapter);
NameRecyclerViewAdapter.java
import android.database.Cursor; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import android.widget.TextView; /** * * Recycler Adapter for TestDB * */ public class NameRecyclerAdapter extends RecyclerView.Adapter{ private Cursor mCursor; @Override public NameViewHolder onCreateViewHolder(ViewGroup parent, int position) { NameViewHolder vh = new NameViewHolder(new TextView(parent.getContext())); return vh; } @Override public void onBindViewHolder(NameViewHolder viewHolder, int position) { mCursor.moveToPosition(position); ((TextView)(viewHolder.itemView)) .setText(mCursor.getString(mCursor.getColumnIndex(TestDb.NAME))); } @Override public int getItemCount() { if (mCursor != null) return mCursor.getCount(); else return 0; } /** * set DataBase Cursor for Recycler Adapter * @param cur */ public void setDataSet(Cursor cur) { mCursor = cur; } }
set DataSet with Db Cursor asynchronously
private class LoadTestDbTask extends AsyncTask{ @Override protected TestDb doInBackground(Context... params) { return new TestDb(params[0]); } @Override protected void onPostExecute(TestDb testDb) { super.onPostExecute(testDb); mAdapter.setDataSet(testDb.getNames()); mAdapter.notifyDataSetChanged(); } }
This sample code is in GitHub.
댓글
댓글 쓰기