Thursday, June 15, 2017

RecyclerView OnClick Listener again

June 15, 2017

RecyclerVIew On Click listener Image
RecyclerView is the more flexible than ListView. Now we all use RecyclerView. But In the RecyclerVIew there is a problem that it's not come with the listener. So we can not handle click event easily. I already post a method to handle click event click here. Here are an another methods to handle click event.
Note: In this post, I just show only some methods where you have to change not full code.

Benefits of the methods are you can use this click listener in your activity, not adapter class.
If you want to learn about full recycle view code like the adapter and viewHolder class sees this post. 

Processes-
 1. First, you need to add an interface (you can add interface in separate interface file or declare in on inner class). I add on Adapter class
public interface ClickListener{
    void onItemClickListener(String s);
}
Note: If you need long click listener then create another method and add on view holder class. I add a method on interface name  OnItemClickListener and add parameter String because we need a string to send another activity.

 2.Now modify the default constructor of adapter class
private ClickListener clickListener;

    /**
     * Constructor for the CustomCursorAdapter
     * @param clickListener to handle click event
     */
    public CustomCursorAdapter(ClickListener clickListener) {
        this.clickListener = clickListener;
    }
3. Implements view.OnClickListener on viewHolder class. See this
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        // Class variables for the task description and priority TextViews
        TextView word;

        /**
         * Constructor for the TaskViewHolders.
         *
         * @param itemView The view inflated in onCreateViewHolder
         */
        private MyViewHolder(View itemView) {
            super(itemView);

            word = (TextView) itemView.findViewById(R.id.mainRecycleView_TV);

            word.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            mCursor.moveToPosition(getAdapterPosition());
            int wordIndex = mCursor.getColumnIndex(COLUMN_WORD);
            String word = mCursor.getString(wordIndex);
            //get word from cursor and set it to click listener parameter
            // we can easily access form click event methods
            clickListener.onItemClickListener(word);
        }
    }
on the Onclick listener method, we take String from array or Cursor and send as our interface method parameter. Now can easily access this string on the main activity. 4. Now time to  Use - implements the interface that's we created earlier,
public class MainActivity extends AppCompatActivity
        implements CustomCursorAdapter.ClickListener {
   

       //some code

}

After that's
/** onClick listener for recycler view
     * called if click any item on recycler view
     * @param word is the selected word from data base
     */
    @Override
    public void onItemClickListener(String word) {
        Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
        intent.putExtra(Intent.EXTRA_TEXT,word);
        startActivity(intent);
}


Using adapter
CustomCursorAdapter mAdapter = new CustomCursorAdapter(this);
recyclerView.setAdapter(mAdapter);

Thanks for reading this post.

I hope your code is running well. And you can handle the click event on RecyclerView more easily. But once again full code post of recyclerview is here.
 If you have any queries then use comment option I will help you.


Happy coding :p

Read More

Thursday, May 18, 2017

Android RecycleView and OnClickListener part 2

May 18, 2017

If you miss Part 1. Please Check Part 1 first by clicking here.

Now come back to your MainActivity.java follow some steps-
  • Create SubjectList type ArrayList
  • Create Adapter and initialize it
  • set adapter to RecyclerView by recyclerView.setAdapter(adapter);
  • at last, fill the array list.
See the code-
public class MainActivity extends AppCompatActivity {

    private ArrayList<SubjectList> arrayList;

    public static final String [] list = {
            "one", "two", "three",
            "four", "five", "six",
            "seven", "eight", "nine",
            "ten", "eleven", "twelve",
            "thirteen", "fourteen", "fifteen",
            "sixteen", "seventeen", "eighteen"

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        fillUpArray();
        
        //initialize adapter
        MainAdapter adapter = new MainAdapter(arrayList,this);

        recyclerView.setAdapter(adapter);

    }

    private void fillUpArray() {

        arrayList = new ArrayList<>();
        
        for (int i = list.length; i > 0 ; i--) {
            SubjectList sub = new SubjectList(list[(list.length)- i]);
            arrayList.add(sub);
        }

    }

}
That’s it. Now revise full code that we use here-

MainActivity.java

1:  package com.blogspot.shudiptotrafder.androidaio;  
2:    
3:  import android.content.Intent;  
4:  import android.os.Bundle;  
5:  import android.support.v7.app.AppCompatActivity;  
6:  import android.support.v7.widget.LinearLayoutManager;  
7:  import android.support.v7.widget.RecyclerView;  
8:  import android.util.Log;  
9:  import android.view.Menu;  
10:  import android.view.MenuItem;  
11:    
12:  import com.blogspot.shudiptotrafder.androidaio.main.MainAdapter;  
13:  import com.blogspot.shudiptotrafder.androidaio.main.SubjectList;  
14:    
15:  import java.util.ArrayList;  
16:    
17:  public class MainActivity extends AppCompatActivity {  
18:    
19:    private ArrayList<SubjectList> arrayList;  
20:    
21:    public static final String[] list = {  
22:        "one", "two", "three",  
23:        "four", "five", "six",  
24:        "seven", "eight", "nine",  
25:        "ten", "eleven", "twelve",  
26:        "thirteen", "fourteen", "fifteen",  
27:        "sixteen", "seventeen", "eighteen"  
28:    
29:    };  
30:    
31:    private static final String logTag = MainActivity.class.getSimpleName();  
32:    
33:    @Override  
34:    protected void onCreate(Bundle savedInstanceState) {  
35:      super.onCreate(savedInstanceState);  
36:      setContentView(R.layout.activity_main);  
37:    
38:      RecyclerView recyclerView = (RecyclerView) findViewById(R.id.main_recyView);  
39:    
40:      fillUpArray();  
41:    
42:      //initialize adapter  
43:      MainAdapter adapter = new MainAdapter(arrayList,this);  
44:    
45:      LinearLayoutManager linearLayoutManager = new  
46:          LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);  
47:    
48:      //setting layout manager  
49:      recyclerView.setLayoutManager(linearLayoutManager);  
50:      recyclerView.setNestedScrollingEnabled(false);  
51:      recyclerView.setAdapter(adapter);  
52:    
53:    }  
54:    
55:    private void fillUpArray() {  
56:    
57:      arrayList = new ArrayList<>();  
58:    
59:    
60:      for (int i = list.length; i > 0 ; i--) {  
61:        SubjectList sub = new SubjectList(list[(list.length)- i]);  
62:        arrayList.add(sub);  
63:        sl(String.valueOf(i));  
64:      }  
65:    
66:    }  
67:    
68:    private static void sl(String string){  
69:      if (BuildConfig.DEBUG){  
70:        Log.e(logTag,string);  
71:      }  
72:    }  
73:    
74:    //for option menu  
75:    @Override  
76:    public boolean onCreateOptionsMenu(Menu menu) {  
77:      // Inflate the menu; this adds items to the action bar if it is present.  
78:      getMenuInflater().inflate(R.menu.menu_main, menu);  
79:      return super.onCreateOptionsMenu(menu);  
80:    }  
81:    
82:    @Override  
83:    public boolean onOptionsItemSelected(MenuItem item) {  
84:    
85:      // Handle action bar item clicks here. The action bar will  
86:      // automatically handle clicks on the Home/Up button, so long  
87:      // as you specify a parent activity in AndroidManifest.xml.  
88:      int id = item.getItemId();  
89:    
90:      //noinspection SimplifiableIfStatement  
91:      if (id == R.id.action_settings) {  
92:        return true;  
93:      }  
94:    
95:      return super.onOptionsItemSelected(item);  
96:    }  
97:  }  
98:    

MainAdapter.java

1:  package com.blogspot.shudiptotrafder.androidaio.main;  
2:    
3:  import android.content.Context;  
4:  import android.content.Intent;  
5:  import android.support.v7.widget.RecyclerView;  
6:  import android.view.LayoutInflater;  
7:  import android.view.View;  
8:  import android.view.ViewGroup;  
9:  import android.widget.TextView;  
10:    
11:  import com.blogspot.shudiptotrafder.androidaio.LocationActivity;  
12:  import com.blogspot.shudiptotrafder.androidaio.R;  
13:  import com.blogspot.shudiptotrafder.androidaio.email.EmailValidationActivity;  
14:  import com.blogspot.shudiptotrafder.androidaio.fab.FabActivity;  
15:  import com.blogspot.shudiptotrafder.androidaio.string.StringFormatActivity;  
16:    
17:  import java.util.ArrayList;  
18:    
19:  /**  
20:   * AndroidAIO  
21:   * com.blogspot.shudiptotrafder.androidaio.main  
22:   * Created by Shudipto Trafder on 1/2/2017 at 10:22 PM.  
23:   * 
24:   */  
25:    
26:  public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {  
27:    
28:    
29:    //Array list  
30:    private ArrayList<SubjectList> objects;  
31:    //context  
32:    private Context context;  
33:    
34:    //view holder class  
35:    class MainViewHolder extends RecyclerView.ViewHolder {  
36:    
37:      TextView textView;  
38:    
39:      private MainViewHolder(View itemView) {  
40:        super(itemView);  
41:        textView = (TextView) itemView.findViewById(R.id.main_card_tv);  
42:      }  
43:    }  
44:    
45:    //constructor  
46:    public MainAdapter(ArrayList<SubjectList> objects, Context context) {  
47:      this.objects = objects;  
48:      this.context = context;  
49:    }  
50:    
51:    @Override  
52:    public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
53:    
54:      View view = LayoutInflater.from(parent.getContext())  
55:          .inflate(R.layout.main_card_view,parent,false);  
56:      return new MainViewHolder(view);  
57:    }  
58:    
59:    @Override  
60:    public void onBindViewHolder(final MainViewHolder holder, int position) {  
61:    
62:      final SubjectList list = objects.get(position);  
63:    
64:      holder.textView.setText(list.getSubName());  
65:      holder.textView.setOnLongClickListener(new View.OnLongClickListener() {  
66:        @Override  
67:        public boolean onLongClick(View v) {  
68:          return false;  
69:        }  
70:      });  
71:    
72:      holder.textView.setOnClickListener(new View.OnClickListener() {  
73:        @Override  
74:        public void onClick(View v) {  
75:        context.startActivity(new Intent(context,EmailValidationActivity.class));  
76:        }  
77:      });  
78:    }  
79:    
80:    @Override  
81:    public int getItemCount() {  
82:      return objects.size();  
83:    }  
84:  }  
85:    
86:    

SubjectList

1:  package com.blogspot.shudiptotrafder.androidaio.main;  
2:    
3:  /**  
4:   * AndroidAIO  
5:   * com.blogspot.shudiptotrafder.androidaio.main  
6:   * Created by Shudipto Trafder on 1/3/2017 at 2:47 PM.  
7:   * 
8:   */  
9:    
10:  public class SubjectList {  
11:    
12:    private String subName;  
13:    
14:    public SubjectList(String subName) {  
15:      this.subName = subName;  
16:    }  
17:    
18:    public String getSubName() {  
19:      return subName;  
20:    }  
21:  }  
22:    

activity_main.xml

1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <RelativeLayout  
3:    xmlns:android="http://schemas.android.com/apk/res/android"  
4:    xmlns:tools="http://schemas.android.com/tools"  
5:    android:id="@+id/activity_main"  
6:    android:layout_width="match_parent"  
7:    android:layout_height="match_parent"  
8:    android:paddingBottom="@dimen/activity_vertical_margin"  
9:    android:paddingLeft="@dimen/activity_horizontal_margin"  
10:    android:paddingRight="@dimen/activity_horizontal_margin"  
11:    android:paddingTop="@dimen/activity_vertical_margin"  
12:    tools:context="com.blogspot.shudiptotrafder.androidaio.MainActivity">  
13:    
14:    <android.support.v7.widget.RecyclerView  
15:      android:layout_width="match_parent"  
16:      android:layout_height="wrap_content"  
17:      android:layout_alignParentTop="true"  
18:      android:padding="10dp"  
19:      android:layout_alignParentStart="true"  
20:      android:id="@+id/main_recyView"/>  
21:    
22:  </RelativeLayout>  

main_card_view.xml

1:  <?xml version="1.0" encoding="utf-8"?>  
2:    
3:  <android.support.v7.widget.CardView  
4:    xmlns:android="http://schemas.android.com/apk/res/android"  
5:    android:layout_width="match_parent"  
6:    android:layout_height="wrap_content"  
7:    android:layout_marginTop="10dp"  
8:    android:elevation="10dp"  
9:    android:padding="10dp">  
10:    
11:    <TextView  
12:      android:id="@+id/main_card_tv"  
13:      android:layout_width="match_parent"  
14:      android:layout_height="wrap_content"  
15:      android:layout_gravity="center"  
16:      android:padding="10dp"  
17:      android:text="@string/app_name"  
18:      android:textSize="20sp"/>  
19:    
20:  </android.support.v7.widget.CardView>  
Now, this is the final picture of our RecyclerView with Simple List.
final picture rcv

Read More

Android RecycleView with OnClickListener

May 18, 2017

Android RecyclerView is more than flexible more than android  ListView. It is a container for rendering larger data set of views that can be recycled and scrolled very efficiently. RecyclerView is like traditional ListView, but with more flexibility to customizes and optimized to work with larger datasets.
Example of Android RecyclerView
recyclerView list main
recyclerView list
First, add the following android support library dependency to project build.graddle file.
dependencies {
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
} 

First, dependency for RecyclerView and Second is for CardView. We use cardView in Recyclerview row item layout file. now use below code to your layout file
<android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/main_recyView"/>

Now go to your java class file and use below code.

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.main_recyView);

LinearLayoutManager linearLayoutManager = new 
LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);

//setting layout manager
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setNestedScrollingEnabled(false);

Here I use LinearLayoutManager and vertically scroll options. you can use another layout manager. Now create an Adapter of android RecyclerView. we also need ViewHolder Class. you can create this ViewHolder class in a separate class or in the child class of Adapter class. I create ViewHolder class in the Adapter class. in adapter class, we need two variables
  1. ArrayList
  2. Context
we also need android Recyclerview row item layout file. code is
<android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:elevation="10dp"
        android:padding="10dp">

        <TextView
            android:id="@+id/main_card_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:padding="10dp"
            android:text="@string/app_name"
            android:textSize="20sp"/>

    </android.support.v7.widget.CardView>
we also need Item type class. My class name is SubjectList.java you can change your choice. SubjectList.java code is
public class SubjectList {

        private String subName;

        public SubjectList(String subName) {
            this.subName = subName;
        }

        public String getSubName() {
            return subName;
        }
    }

Now adapter class
public class MainAdapter extends    RecyclerView.Adapter<MainAdapter.MainViewHolder> {


        //Array list
        private ArrayList<SubjectList> objects;
        //context
        private Context context;

        //view holder class
        class MainViewHolder extends RecyclerView.ViewHolder {

            TextView textView;

            private MainViewHolder(View itemView) {
                super(itemView);
                textView = (TextView) itemView.findViewById(R.id.main_card_tv);
            }
        }

        //constructor
        public MainAdapter(ArrayList<SubjectList> objects, Context context) {
            this.objects = objects;
            this.context = context;
        }

        @Override
        public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.main_card_view,parent,false);
            return new MainViewHolder(view);
        }

    @Override
    public void onBindViewHolder(final MainViewHolder holder, int position) {

        final SubjectList list = objects.get(position);

        holder.textView.setText(list.getSubName());

        holder.textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(new Intent(context, LocationActivity.class));
                
            }
        });
    }

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

}

RecyclerView OnclickListener

we add a listener in onBindViewHolder method. the code here-
@Override
        public void onBindViewHolder(final MainViewHolder holder, int position) {

            final SubjectList list = objects.get(position);
            
            holder.textView.setText(list.getSubName());

            holder.textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context.startActivity(new Intent(context, LocationActivity.class));
                
            }
        });
            holder.textView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return false;
            }
        });
    }
Note: If you have multiple views in Recyclerview row item layout file you can use Card view to setOnClickListener instead of Textview.

Code analysis

ViewHolder Class-
  • we make ViewHolder class extend of RecyclerView.ViewHolder
  • we have on TextView and we cast it.
that’s all of ViewHolder Class. Adapter class-
  • we initialize our two variables through constructor
  • in onCreateViewHolder methods we create a new view type that inflates a layout file through LayoutInflater and returns new ViewHolder class with a parameter with that’s view.
  • we create new SubjectList and initialize it through the position of the ArrayList item.
  • add set Text to View by getting getter method of SubjectList.
  • now setOnClickListener to the view
  • in final we just return the size of ArrayList in getItemCount() method.

Please check next Part. Next Part cover MainActivity code Revise of all code and final screenshot. Click here.

Read More