Friday, May 27, 2016

Android with RecyclerView Example

RecyclerView is more advanced and flexible and efficient version of ListView. RecyclerView ViewGroup is an container for larger data set of views that can be recycled and scrolled very efficiently. RecyclerView can be used for larger datasets to be rendered on the UI like a list. RecyclerView provides maximum flexibility to design different kind of views.

Android RecyclerView is more advanced version of ListView with improved performance and other benefits. Using RecyclerView and CardView together, both lists and grids can be created very easily.

You have to include the dependencies in gradle file like this.


build.gradle
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
}

1) Activity

import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class CommonForumActivity extends AppCompatActivity {

    public ListView list;
    public CustomAdapter adapter;
    public  CommonForumActivity CustomListView = null;
    public ArrayList<ForumModel> CustomListViewValuesArr = new ArrayList<ForumModel>();


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

        CustomListView = this;

        /******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/        setListData();

        Resources res =getResources();
        list= ( ListView )findViewById( R.id.listView );  // List defined in XML ( See Below )
        /**************** Create Custom Adapter *********/        adapter=new CustomAdapter( CustomListView, CustomListViewValuesArr,res );
        list.setAdapter( adapter );
    }

    /****** Function to set data in ArrayList *************/    public void setListData()
    {

        for (int i = 0; i < 11; i++) {

            final ForumModel sched = new ForumModel();

            /******* Firstly take data in model object ******/            sched.setQuestion("Company " + i);
            sched.setImageUrl("image" + i);
            /******** Take Model Object in ArrayList **********/            CustomListViewValuesArr.add( sched );
        }

    }

    public void OnItemClickListener(int mPosition)
    {
        ForumModel tempValues = ( ForumModel ) CustomListViewValuesArr.get(mPosition);

    }
}

2) Forum Model:

/** * Created by Abhinaw.Tripathi on 24-05-2016. */public class ForumModel {

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    private String question="";
    private String imageUrl ="";
}

3)CustomeAdapter

import java.util.ArrayList;

/** * Created by Abhinaw.Tripathi on 24-05-2016. */public class CustomAdapter extends BaseAdapter implements View.OnClickListener
{
    private Activity activity;
    private ArrayList data;
    private static LayoutInflater inflater=null;
    public Resources res;
    ForumModel tempValues=null;
    int i=0;

    /*************  CustomAdapter Constructor *****************/    public CustomAdapter(Activity a, ArrayList d,Resources resLocal)
    {
        /********** Take passed values **********/        activity = a;
        data=d;
        res = resLocal;
        /***********  Layout inflator to call external xml layout () ***********/        inflater = ( LayoutInflater )activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }


    @Override    public int getCount()
    {
        if(data.size()<=0)
            return 1;
        return data.size();
    }

    @Override    public Object getItem(int position) {
        return position;
    }

    @Override    public long getItemId(int position) {
        return position;
    }

    /********* Create a holder Class to contain inflated xml file elements *********/    public static class ViewHolder
    {
        public TextView text;
        public ImageView image;
        public TextView answer;
    }

    @Override    public View getView(int position, View convertView, ViewGroup parent)
    {
        View vi = convertView;
        ViewHolder holder;

        if(convertView==null) {

            /****** Inflate tabitem.xml file for each row ( Defined below ) *******/            vi = inflater.inflate(R.layout.item_row_layout, null);

            /****** View Holder Object to contain tabitem.xml file elements ******/
            holder = new ViewHolder();
            holder.text = (TextView) vi.findViewById(R.id.txt_row_ask_quest);
            holder.image = (ImageView) vi.findViewById(R.id.imgView_titleHardCodeQyuest);
            holder.answer = (TextView) vi.findViewById(R.id.txt_titleHardCodeAns);

            /************  Set holder with LayoutInflater ************/            vi.setTag(holder);
        }
        else            holder=(ViewHolder)vi.getTag();
        if(data.size()<=0)
        {
            holder.text.setText("No Data");

        }
        else        {
            /***** Get each Model object from Arraylist ********/            tempValues=null;
            tempValues = ( ForumModel ) data.get( position );

            /************  Set Model values in Holder elements ***********/
            holder.text.setText( tempValues.getQuestion());
            holder.image.setImageResource(
                    res.getIdentifier(
                            "com.myandroid.docpat:drawable/" + tempValues.getImageUrl()
                            , null, null));
            /******** Set Item Click Listner for LayoutInflater for each row *******/
            vi.setOnClickListener((View.OnClickListener) new OnItemClickListener( position ));

        }
        return vi;
    }

    @Override    public void onClick(View v) {

    }

    /********* Called when Item click in ListView ************/    private class OnItemClickListener  implements View.OnClickListener {
        private int mPosition;

        OnItemClickListener(int position){
            mPosition = position;
        }

        @Override        public void onClick(View arg0) {

            CommonForumActivity sct = (CommonForumActivity)activity;

            sct.OnItemClickListener(mPosition);

        }
    }
}

4)item_row_layout

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="wrap_content"    >
    <LinearLayout        android:orientation="horizontal"        android:layout_width="match_parent"        android:weightSum="2.0"        android:layout_height="wrap_content">

    <ImageView        android:layout_width="100dp"        android:layout_height="80dp"        android:layout_weight="0.5"        android:id="@+id/imgView_titleHardCodeQyuest"        android:textColor="@android:color/black"        android:onClick="onClick"        android:background="@drawable/questions"        />
        <TextView            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_weight="1.5"            android:text="what is your question?"            android:textStyle="bold"            android:textSize="20dp"            android:gravity="center_horizontal|center_vertical|center"
            android:id="@+id/txt_row_ask_quest"            android:textColor="@android:color/black"            android:onClick="onClick"            />


    </LinearLayout>

    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Answer:"        android:textStyle="bold"        android:padding="20dp"        android:textSize="20dp"        android:id="@+id/txt_titleHardCodeAns"        android:textColor="@android:color/black"        android:onClick="onClick"        />


</LinearLayout>

5)mainlayout:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    android:layout_margin="5dp"    tools:context="com.myandroid.docpat.CommonForumActivity"    android:background="@drawable/border"    >

    <TextView        android:id="@+id/txt_titleForum"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text=" Please ask questions or doubts!!!"        android:textStyle="bold"        android:padding="20dp"        android:background="@android:color/darker_gray"        android:textSize="20dp"        android:textColor="@android:color/black"        android:singleLine="false"        android:layout_centerHorizontal="true"        />

    <ListView        android:id="@+id/listView"        android:layout_below="@+id/txt_titleForum"        android:layout_above="@+id/bottomLayout"        android:layout_width="match_parent"        android:layout_height="wrap_content">

    </ListView>


<LinearLayout    android:id="@+id/bottomLayout"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:orientation="horizontal"    android:weightSum="3.0"    android:layout_alignParentBottom="true"    android:background="@android:color/darker_gray"    >

    <Button        android:id="@+id/btnAskQuest"        android:text="Ask Question"        android:layout_margin="5dp"        android:layout_width="wrap_content"        android:layout_weight="1.0"        android:layout_height="wrap_content" />

    <Button        android:id="@+id/btnGiveAns"        android:text="Give Answer"        android:layout_margin="5dp"        android:layout_width="wrap_content"        android:layout_weight="1.0"        android:layout_height="wrap_content" />
    <Button        android:id="@+id/btnDo_Nothing"        android:text="Do Nothing"        android:layout_margin="5dp"        android:layout_width="wrap_content"        android:layout_weight="1.0"        android:layout_height="wrap_content" />

</LinearLayout>

</RelativeLayout>

No comments: