Thursday, January 5, 2017

Recycler View in Android

Recycler view in android is use for show data like a listview .

add build gradel : 


compile 'com.android.support:recyclerview-v7:24.1.1'

XML Define RecyclerView

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


RecyclerView mRecyclerView;
LinearLayoutManager linearLayoutManager;

ArrayList<Model> arrayList = null;

Initialize : 
arrayList = new ArrayList<>();  // array initialize

mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);


arrayList.add(new Model("Android")); // add static data to array
arrayList.add(new Model("iPhone"));
arrayList.add(new Model("Window"));
arrayList.add(new Model("Blackberry"));
arrayList.add(new Model("Symbion"));

adapter = new CustomAdapter(this, arrayList); // show data
mRecyclerView.setAdapter(adapter);  // set adapter

Now discuss about adapter :  

class CustomAdapter extends RecyclerView.Adapter<CustomAdapter .ViewHolder> {

    ArrayList<HomeModel> arrayList;

    public CustomAdapter (ArrayList<HomeModel> arrayList) {
        this.arrayList = arrayList;
    }

    @Override    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override    public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
       viewHolder.title.setText(arrayList.get(position).getTitle());

    }

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

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView title;

        public ViewHolder(View convertView) {
            super(convertView);
            title = (TextView) convertView.findViewById(R.id.title);
        }
    }


Custom Model Class

lass HomeModel {

    String title;

    public HomeModel(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }