Implement OnItemLongClickLister in RecyclerView - android

i am working on one project in which i have used open source code, but at one point i am stuck, in this code i am using RecyclerView in which onRecycleItemClickListener is already implemented but now i need to implement onItemLongClickListener in existing code
public abstract class BaseRecyclerViewAdapter<T, VH extends BaseClickListenerViewHolder> extends RecyclerView.Adapter<VH> {
private List<T> objectsList;
protected final BaseActivity baseActivity;
protected final LayoutInflater layoutInflater;
protected final Resources resources;
protected QBUser currentQbUser;
// Package private because we need access in BaseViewHolder but not in child classes
OnRecycleItemClickListener<T> onRecycleItemClickListener;
AdapterView.OnItemLongClickListener onItemLongClickListener;
public BaseRecyclerViewAdapter(BaseActivity baseActivity) {
this.baseActivity = baseActivity;
this.layoutInflater = LayoutInflater.from(baseActivity);
resources = baseActivity.getResources();
objectsList = new ArrayList<>();
}
public BaseRecyclerViewAdapter(BaseActivity baseActivity, List<T> objectsList) {
this(baseActivity);
this.objectsList = objectsList;
currentQbUser = AppSession.getSession().getUser();
}
public void setList(List<T> items) {
objectsList = items;
notifyDataSetChanged();
}
public void addItem(T item) {
objectsList.add(item);
notifyItemInserted(objectsList.size() - 1);
}
public void addItem(int position, T item) {
objectsList.add(position, item);
notifyItemInserted(position);
}
public void addAll(Collection<T> collection) {
objectsList.addAll(collection);
notifyItemRangeChanged(objectsList.size() - collection.size(), collection.size());
}
public void removeItem(int position) {
objectsList.remove(position);
notifyItemRemoved(position);
}
public void removeItem(T item) {
int position = objectsList.indexOf(item);
if (position != -1) {
objectsList.remove(item);
notifyItemRemoved(position);
}
}
public void clear() {
objectsList.clear();
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return objectsList.size();
}
public T getItem(int position) {
return objectsList.get(position);
}
public List<T> getAllItems() {
return objectsList;
}
public boolean isEmpty() {
return objectsList.size() == 0;
}
public void setOnRecycleItemClickListener(OnRecycleItemClickListener<T> onRecycleItemClickListener) {
this.onRecycleItemClickListener = onRecycleItemClickListener;
}
protected void displayAvatarImage(String uri, ImageView imageView) {
ImageLoader.getInstance().displayImage(uri, imageView, ImageLoaderUtils.UIL_USER_AVATAR_DISPLAY_OPTIONS);
}
}

You can use this class ItemTouchListenerAdapter in your code to easily add support for both item clicks and long-clicks.
Usage:
recyclerView.addOnItemTouchListener(new ItemTouchListenerAdapter(recyclerView, this));
Code:
public class ItemTouchListenerAdapter extends GestureDetector.SimpleOnGestureListener implements RecyclerView.OnItemTouchListener {
public interface RecyclerViewOnItemClickListener {
void onItemClick(RecyclerView parent, View clickedView, int position);
void onItemLongClick(RecyclerView parent, View clickedView, int position);
}
private RecyclerViewOnItemClickListener listener;
private RecyclerView recyclerView;
private GestureDetector gestureDetector;
public ItemTouchListenerAdapter(RecyclerView recyclerView, RecyclerViewOnItemClickListener listener) {
if (recyclerView == null || listener == null) {
throw new IllegalArgumentException("RecyclerView and Listener arguments can not be null");
}
this.recyclerView = recyclerView;
this.listener = listener;
this.gestureDetector = new GestureDetector(recyclerView.getContext(), this);
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
gestureDetector.onTouchEvent(motionEvent);
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onShowPress(MotionEvent e) {
View view = getChildViewUnder(e);
if (view != null) {
view.setPressed(true);
}
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
View view = getChildViewUnder(e);
if (view == null) return false;
view.setPressed(false);
int position = recyclerView.getChildPosition(view);
listener.onItemClick(recyclerView, view, position);
return true;
}
public void onLongPress(MotionEvent e) {
View view = getChildViewUnder(e);
if (view == null) return;
int position = recyclerView.getChildPosition(view);
listener.onItemLongClick(recyclerView, view, position);
view.setPressed(false);
}
#Nullable
private View getChildViewUnder(MotionEvent e) {
return recyclerView.findChildViewUnder(e.getX(), e.getY());
}
}

Related

RecyclerView clickListener is not working

I've implemented the recyclerView clicklistener using best practices yet it still isn't working. The recyclerview is loading data from the internet using retrofit and should take users to the site where the article was published below is my code:
NOTE: My RecyclerView is a RecyclerView of Cardviews
RecyclerView Adapter
public class NewsArticleAdapter extends RecyclerView.Adapter<NewsArticleAdapter.Viewholder> {
private ArrayList<Article> newsArticles = new ArrayList<>();
private Context context;
private OnArticleListener onArticleListener;
public NewsArticleAdapter(List<Article> newsArticles, Context context, OnArticleListener onArticleListener) {
this.newsArticles = (ArrayList<Article>) newsArticles;
this.context = context;
this.onArticleListener = onArticleListener;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_list_item, parent, false);
Viewholder viewholder = new Viewholder(view, onArticleListener);
return viewholder;
}
#Override
public void onBindViewHolder(#NonNull Viewholder holder, int position) {
Article currentArticle = newsArticles.get(position);
holder.newsHeadline.setText(currentArticle.getTitle());
Glide.with(context)
.load(currentArticle.getUrlToImage())
.placeholder(R.drawable.ic_launcher_foreground)
.into(holder.newsImage);
holder.newsContent.setText(currentArticle.getContent());
// holder.publishedTime.setText(UTCtoLocalDateConverter(currentArticle.getPublishedAt()));
}
#Override
public int getItemCount() {
return newsArticles.size();
}
public class Viewholder extends RecyclerView.ViewHolder implements View.OnClickListener {
OnArticleListener onArticleClickedListner;
TextView newsHeadline;
TextView newsContent;
// TextView publishedTime;
ImageView newsImage;
ConstraintLayout parentLayout;
public Viewholder(#NonNull View itemView, OnArticleListener onArticleListener) {
super(itemView);
newsHeadline = itemView.findViewById(R.id.news_headline_textView);
newsContent = itemView.findViewById(R.id.news_content_textView);
// publishedTime = itemView.findViewById(R.id.published_time_textView);
newsImage = itemView.findViewById(R.id.news_image_view);
parentLayout = itemView.findViewById(R.id.list_item_parent_layout);
onArticleClickedListner = onArticleListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Log.d("RecyclerViewAdapter", "item position clicked: " + getAdapterPosition());
onArticleClickedListner.onArticleClicked(getAdapterPosition());
}
}
/*RecyclerView onItemClickListenerInterface*/
public interface OnArticleListener {
void onArticleClicked(int position);
}
}
MainActivity (Houses RecyclerView)
public class MainActivity extends AppCompatActivity implements NewsArticleAdapter.OnArticleListener {
private RecyclerView newsRecyclerView;
private NewsArticleAdapter newsAdapter;
private NewsAPI NewsAPI;
private ArrayList<Article> newsArticles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newsRecyclerView = findViewById(R.id.newsRecyclerView);
newsAdapter = new NewsArticleAdapter(new ArrayList<Article>(), this, this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
newsRecyclerView.setLayoutManager(layoutManager);
newsRecyclerView.setAdapter(newsAdapter);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RetrofitClient.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
NewsAPI = retrofit.create(NewsAPI.class);
Call<Example> call = NewsAPI.getRootJSONObject();
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
if (response.isSuccessful()) {
newsArticles = (ArrayList<Article>) response.body().getArticles();
refreshAdapterWithNewsArticles(newsArticles);
} else {
Log.d("MainActivity", "Error in on Response " + String.valueOf(response.code()));
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Toast.makeText(MainActivity.this, "Error retrieving News Articles :(", Toast.LENGTH_SHORT).show();
}
});
}
/*
*Method used to generate list of data using recyclerView with costom adapter
* */
private void refreshAdapterWithNewsArticles(List<Article> body) {
newsAdapter = null;
newsAdapter = new NewsArticleAdapter(body, this, MainActivity.this);
newsRecyclerView.setAdapter(newsAdapter);
}
#Override
public void onArticleClicked(int position) {
Log.d("MainActivity", "onArticleClicked Was called in MainACtivity");
Article currentArticle = newsArticles.get(position);
Uri articleUri = Uri.parse(currentArticle.getUrl());
Intent intent = new Intent(Intent.ACTION_VIEW, articleUri);
startActivity(intent);
}
}
Inspired by the code provided in this answer from Jacob Tabak, in your mainActivity under onCreate method.
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(MainActivity.this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
//whatever you want to do with position
}
#Override
public void onLongItemClick(View view, int position) {
//whatever you want to do with position
}
}));
and create a new class name it RecyclerItemClickListener
and paste this
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
GestureDetector mGestureDetector;
private OnItemClickListener mListener;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && mListener != null) {
mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onLongItemClick(View view, int position);
}}
It is a custom RecyclerItemClickListener.
Why don't you try the listener from the onBindViewHolder() method?
holder.your_layout_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onArticleClickedListner.onArticleClicked(position);
}
});
If you have any confusion I can explain it more clear. If you solved it you can accept the answer.

How to get value from adapter to activity on recyclerview item click event in Android?

I'm learning RecyclerView and I built an app that can populate simple data from SQLite database
I have an Adapter as follows :-
public class BookAdapter extends RecyclerView.Adapter<BookAdapter.BookViewHolder> {
Context mContext;
Cursor mCursor;
OnBookListener mOnBookListener;
public int id;
public BookAdapter(Context context, Cursor cursor, OnBookListener onBookListener){
mContext = context;
mCursor = cursor;
mOnBookListener = onBookListener;
}
public class BookViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView id_textView, name_textView;
OnBookListener onBookListener;
public BookViewHolder(#NonNull View itemView, OnBookListener onBookListener) {
super(itemView);
id_textView = itemView.findViewById(R.id.book_id);
name_textView = itemView.findViewById(R.id.book_name);
this.onBookListener = onBookListener;
itemView.setOnClickListener(this);
}
public String getId_textView() {
return (String)id_textView.getText();
}
public String getName_textView() {
return (String)name_textView.getText();
}
#Override
public void onClick(View v) {
onBookListener.onBookClick((String)id_textView.getText());
//Log.d(TAG, "onBookClick : Clicked " + id_textView.getText());
}
}
public interface OnBookListener{
void onBookClick(String id);
}
#NonNull
#Override
public BookViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.book_item,parent,false);
return new BookViewHolder(view, mOnBookListener);
}
#Override
public void onBindViewHolder(#NonNull BookViewHolder holder, int position) {
if(!mCursor.moveToPosition(position)){
return;
}
id = mCursor.getInt(mCursor.getColumnIndex(Book.BookEntry.COLUMN_ID));
String name = mCursor.getString(mCursor.getColumnIndex(Book.BookEntry.COLUMN_NAME));
holder.id_textView.setText(String.valueOf(id));
holder.name_textView.setText(name);
if(position %2 == 1)
{
holder.itemView.setBackgroundColor(Color.parseColor("#E9EEF3"));
}
else
{
holder.itemView.setBackgroundColor(Color.parseColor("#0FA9E8"));
}
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
public void swapCursor(Cursor newCursor){
if(mCursor != null){
mCursor.close();
}
mCursor = newCursor;
if(newCursor != null){
notifyDataSetChanged();
}
}
now with the Activity itself :
public class MainActivity extends AppCompatActivity implements BookAdapter.OnBookListener {
public SQLiteDatabase mdatabase;
public BookAdapter madapter;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//SqliteDBHelper dbHelper = new SqliteDBHelper(this);
SqliteAssetHelper dbHelper = new SqliteAssetHelper(this);
mdatabase = dbHelper.getReadableDatabase();
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
madapter = new BookAdapter(this, getAllBooks(), this);
recyclerView.setAdapter(madapter);
madapter.swapCursor(getAllBooks());
}
private Cursor getAllBooks(){
return mdatabase.query(Book.BookEntry.TABLE_NAME,null,null,null
,null,null,null);
}
#Override
public void onBookClick(String id) {
Intent intent = new Intent(this, HadithsList.class);
intent.putExtra("id", ???);
startActivity(intent);
}
What code can I replace the question marks in the above intent to actually get the id from the interface : OnBookListener That is implemented in the activity.
Thanks in advance
Assuming you want to pass an id to the next Activity, and assuming the followinf line retrieve the id you want
onBookListener.onBookClick((String)id_textView.getText());
Then, the id is your parameter, so you just have to do this
intent.putExtra("id", id);
Create this class
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener
{
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
handle onClick
recyclerView.addOnItemTouchListener(new
RecyclerTouchListener(getApplicationContext(), recyclerView, new
RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
MealListModel model = myList.get(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));

How to delete value on variable

I am new to Android and I have a question.
I have a recyclerview that can be clicked and will send a query. When clicked, it will get a number/ID of each position that is clicked,
like this:
fno = arrivals.get(position).flightno;
codeCity = arrivals.get(position).arr;
When clicked for the first time it succeeds, but when clicked for the second or third time, it gets an error. I think this because the variable fno and codeCity has been filled. So how to delete the value on the variable?
This my code when the recyclerview clicked:
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() {
public boolean onSingleTapUp(MotionEvent e){
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && gestureDetector.onTouchEvent(e)){
int position = rv.getChildAdapterPosition(child);
fno = arrivals.get(position).flightno;
codeCity = arrivals.get(position).arr;
final Bundle i = new Bundle();
i.putString("city", codeCity.toString()); // Key1
i.putString("flightno", fno.toString()); // Key1
open2(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
This the query
public void open2(Bundle args) {
codeIata = args.getString("city");
String flightdate = args.getString("flightdate");
fno = args.getString("flightno");
ArrivalActivity.detail(codeIata, flightdate, fno);
}
public static void detail(String s, String date, String fno) {
DateFormat df = new SimpleDateFormat("yyyy-MM-d");
date = df.format(Calendar.getInstance().getTime());
Call<GetArrivals> arrCall = mApiInterface.getArr(s, "2019-03-04", "", fno);
arrCall.enqueue(new Callback<GetArrivals>() {
#Override
public void onResponse(Call<GetArrivals> call, Response<GetArrivals>
response) {
System.out.println("status code "+response.code());
arrivals = response.body().getResult();
mAdapter = new ArrivalAdapter(mContext, arrivals);
//mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onFailure(Call<GetArrivals> call, Throwable t) {
Log.e("Retrofit Get", t.toString());
}
});
}
Thank you!
There are two approaches you can capture a click event on item of a recyclerview:
First approach
override onClick method instead of onInterceptTouchEvent.
I am providing you with an example.
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
recyclerView, new ClickListener() {
#Override
public void onClick(View view, final int position) {
fno = arrivals.get(position).flightno;
codeCity = arrivals.get(position).arr;
}
}));
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
Second Approach(a more conventional one)
override the OnClickListener of the viewholder of your adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
LayoutInflater inflater;
Context context;
private MyAdapter.RecyclerViewClickListener mListener;
public MyAdapter(Context context, RecyclerViewClickListener mListener) {
this.context = context;
this.mListener = mListener;
inflater = LayoutInflater.from(this.context);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public MyViewHolder(View item, RecyclerViewClickListener listener) {
super(item);
mListener = listener;
item.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mListener.onClick(view, getAdapterPosition());
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.mylayout, parent, false);
return new MyViewHolder(itemView,mListener);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return youylist.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int position) {
return 0;
}
public interface RecyclerViewClickListener {
void onClick(View view, int position);
}
}
and in your Fragment/Activity:
myadapter = new MyAdapter(getContext(), new MyAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
fno = arrivals.get(position).flightno;
codeCity = arrivals.get(position).arr;
}
});
recyclerView.setAdapter(MyAdapter);
MyAdapter.notifyDataSetChanged();
Hope this helps you.

Recyclerview row item selection color change

I am able to change the color of the text and background of imageview of the row clicked of my recyclerview in my navigation drawer fragment.
But my problem is after clicking the 4th item,the 1st item also gets selected.Likewise after clicking my 5th item the 2nd item is selected.
Like this:
How do i solve this? So that only one item is selected at a time?
FragmentDrawer.java
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
int[] icons = {R.drawable.ic_home,
R.drawable.ic_upcoming,
R.drawable.ic_saved,
R.drawable.ic_wehappened,
R.drawable.ic_persons,
R.drawable.ic_music,
R.drawable.ic_parties,
R.drawable.ic_art, R.drawable.ic_network, R.drawable.ic_sports};
// preparing navigation drawer items
for (int i = 0; i < titles.length && i < icons.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
navItem.setIcon(icons[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
//Sections
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(5, "Categories"));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
NavigationDrawerAdapter.selected_item = position;
recyclerView.getAdapter().notifyDataSetChanged();
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(getContext(), R.layout.section, R.id.section_text, adapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
//Apply this adapter to the RecyclerView
recyclerView.setAdapter(mSectionedAdapter);
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
NavigationDrawerAdapter.java
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public static int selected_item = 0;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(position == selected_item)
{
holder.title.setTextColor(Color.parseColor("#00aaff"));
holder.imgViewIcon.setBackgroundResource(R.drawable.ic_circle);
}
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
holder.imgViewIcon.setImageResource(current.getIcon());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public ImageView imgViewIcon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
imgViewIcon = (ImageView) itemView.findViewById(R.id.item_icon);
}
}
}
EDIT: SimpleSectionedRecyclerViewAdapter.java
public class SimpleSectionedRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context mContext;
private static final int SECTION_TYPE = 0;
private boolean mValid = true;
private int mSectionResourceId;
private int mTextResourceId;
private LayoutInflater mLayoutInflater;
private RecyclerView.Adapter mBaseAdapter;
private SparseArray<Section> mSections = new SparseArray<Section>();
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSectionResourceId = sectionResourceId;
mTextResourceId = textResourceId;
mBaseAdapter = baseAdapter;
mContext = context;
mBaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
mValid = mBaseAdapter.getItemCount()>0;
notifyDataSetChanged();
}
#Override
public void onItemRangeChanged(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeChanged(positionStart, itemCount);
}
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeInserted(positionStart, itemCount);
}
#Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeRemoved(positionStart, itemCount);
}
});
}
public static class SectionViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public SectionViewHolder(View view,int mTextResourceid) {
super(view);
title = (TextView) view.findViewById(mTextResourceid);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int typeView) {
if (typeView == SECTION_TYPE) {
final View view = LayoutInflater.from(mContext).inflate(mSectionResourceId, parent, false);
return new SectionViewHolder(view,mTextResourceId);
}else{
return mBaseAdapter.onCreateViewHolder(parent, typeView -1);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder sectionViewHolder, int position) {
if (isSectionHeaderPosition(position)) {
((SectionViewHolder)sectionViewHolder).title.setText(mSections.get(position).title);
}else{
mBaseAdapter.onBindViewHolder(sectionViewHolder,sectionedPositionToPosition(position));
}
}
#Override
public int getItemViewType(int position) {
return isSectionHeaderPosition(position)
? SECTION_TYPE
: mBaseAdapter.getItemViewType(sectionedPositionToPosition(position)) +1 ;
}
public static class Section {
int firstPosition;
int sectionedPosition;
CharSequence title;
public Section(int firstPosition, CharSequence title) {
this.firstPosition = firstPosition;
this.title = title;
}
public CharSequence getTitle() {
return title;
}
}
public void setSections(Section[] sections) {
mSections.clear();
Arrays.sort(sections, new Comparator<Section>() {
#Override
public int compare(Section o, Section o1) {
return (o.firstPosition == o1.firstPosition)
? 0
: ((o.firstPosition < o1.firstPosition) ? -1 : 1);
}
});
int offset = 0; // offset positions for the headers we're adding
for (Section section : sections) {
section.sectionedPosition = section.firstPosition + offset;
mSections.append(section.sectionedPosition, section);
++offset;
}
notifyDataSetChanged();
}
public int positionToSectionedPosition(int position) {
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).firstPosition > position) {
break;
}
++offset;
}
return position + offset;
}
public int sectionedPositionToPosition(int sectionedPosition) {
if (isSectionHeaderPosition(sectionedPosition)) {
return RecyclerView.NO_POSITION;
}
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).sectionedPosition > sectionedPosition) {
break;
}
--offset;
}
return sectionedPosition + offset;
}
public boolean isSectionHeaderPosition(int position) {
return mSections.get(position) != null;
}
#Override
public long getItemId(int position) {
return isSectionHeaderPosition(position)
? Integer.MAX_VALUE - mSections.indexOfKey(position)
: mBaseAdapter.getItemId(sectionedPositionToPosition(position));
}
#Override
public int getItemCount() {
return (mValid ? mBaseAdapter.getItemCount() + mSections.size() : 0);
}
}
Change the onBindViewHolder method of your NavigationDrawerAdapter.java into this:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(position == selected_item) {
holder.title.setTextColor(Color.parseColor("#00aaff"));
holder.imgViewIcon.setBackgroundResource(R.drawable.ic_circle);
} else {
holder.title.setTextColor(Color.parseColor("#00000")); //actually you should set to the normal text color
holder.imgViewIcon.setBackgroundResource(0);
}
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
holder.imgViewIcon.setImageResource(current.getIcon());
}
Simple and Best
Inside Adapter class
int row_index=0;
inside onBindViewHOlder
holder.titleLL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
row_index=position;
notifyDataSetChanged();
}
});
if (row_index==position) {
holder.title.setTextColor(Color.RED);
} else {
holder.title.setTextColor(Color.BLACK);
}
You can use class for Recycler view TouchListener
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
RecyclerView.ViewHolder viewHolder=rv.findContainingViewHolder(child);
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child),viewHolder);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
Implement an Interface
public interface ClickListener{
public void onClick(View view, int position,RecyclerView.ViewHolder viewHolder);
public void onLongClick(View view, int position);
}
And in your Main Activity (Here I set Image resource You can set as You like ,Any thing)
Create an arraylist named "selected" as Integer and add following code as OnClickListener
recyclerViewSchedule.addOnItemTouchListener(new RecyclerTouchListener(this,
recyclerViewSchedule, new ClickListener() {
#Override
public void onClick(View view, final int position, RecyclerView.ViewHolder v) {
//Values are passing to activity & to fragment as well
if(!selected.contains(position))
{
selected.add(position);
((ScheduleAdapter.MyHolder) v).txtImage.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}else {
((ScheduleAdapter.MyHolder) v).txtImage.setBackgroundColor(getResources().getColor(R.color.colorTransparent));
selected.remove(new Integer(position));
}
Toast.makeText(ScheduleActivity.this, "Single Click on position :"+position,
Toast.LENGTH_SHORT).show();
}
Toast.makeText(ScheduleActivity.this, "Single Click on position :"+position,
Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(ScheduleActivity.this, "Long press on position :"+position,
Toast.LENGTH_LONG).show();
}
}));
The txtImage I specified here is from RecyclerAdapter,Replace it with Your View
Happy Coding :-)
most of the answers for such a question, are about to Override Onclick in onBindViewHolder or implementing an interface for clicking in recycler view. but as we all know, onBindViewHolder is called as your views are populated during scrolling. Thus, you will have numerous calls to setOnClickListener so it is not an efficient way and also implementing interface is not as easy as the answer I got.
here is how you can access selecting items in recycler view and change its background or do what ever you want when an item is selected .
in your ViewHolder constructor use setOnTouchListener for itemView (the argument of constructor) in this way
itemView.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.getTag() == null) {
v.setTag(true);
v.setBackgroundColor(Color.parseColor("#F31807"));
}
else {
v.setBackgroundColor(Color.TRANSPARENT);
v.setTag(null);
}
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
//default color
v.setBackgroundColor(Color.TRANSPARENT);
}
return true;
});
We use ACTION_UP for check if user pressed the item and after that we save a boolean in view's flag so that we can press every items how many times we want and see the color is changing. ACTION_MOVE if block is for prevent selecting items when scrolling the recycler view. if you see that selecting one item is affecting another items selection, you can use this answer:
issue : RecyclerView messed up data when scrolling
in the end if you are curious about why we return true in method see this video to understand.
tutorial on OnTouchListener And Motionevent
I have tried many different approaches but in the end, the solution that worked for me is
like first I was doing this
binding.download.setOnClickListener {
binding.download.visibility = View.GONE
binding.saved.visibility = View.VISIBLE
}
this was not working for me but after the below change
Instead of changing the color or visibility in onBindViewHolder, make a function in ViewHolder class and call it from onBindViewHolder
class ViewHolder(var binding: ImageRowBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(uri: Uri, mContext: Context) {
binding.download.setOnClickListener {
binding.download.visibility = View.GONE
binding.saved.visibility = View.VISIBLE
}
}
}
and calling this bind method from onBindViewHolder like this
holder.bind(items[position].uri, mContext)
works best for me

Item click listeners for RecyclerView

I have been trying to work on RecycleView item click listener. I have come up with following solution. I would like to know if this solution is correct or just a "hack".
public class CityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private int lastPosition = -1;
private int focusedItem = 0;
private static Interfaces.OnCityItemClickListener cityItemClickListner;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView cityNameTextView, tempTextView, humidityTextView, timeTextView;
private ImageView weatherStatusImageView;
private CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
cityNameTextView = (TextView) itemView.findViewById(R.id.city_name_tv);
tempTextView = (TextView) itemView.findViewById(R.id.temp_tv);
humidityTextView = (TextView) itemView.findViewById(R.id.humidity_tv);
timeTextView = (TextView) itemView.findViewById(R.id.time_tv);
cardView = (CardView) itemView.findViewById(R.id.card_view);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
cityItemClickListner.onCityItemClick(getAdapterPosition(), v);
}
}
public CityListAdapter(Context context){
this.context = context;
}
public void setOnCityItemClickListener(Interfaces.OnCityItemClickListener clickListener){
cityItemClickListner = clickListener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_city, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ViewHolder myViewHolder = (ViewHolder) holder;
myViewHolder.itemView.setSelected(focusedItem == position);
}
#Override
public int getItemCount() {
return 15;
}
}
Then in my Activity
adapter.setOnCityItemClickListener(new Interfaces.OnCityItemClickListener() {
#Override
public void onCityItemClick(int position, View view) {
Toast.makeText(BaseActivity.this, "Clicked position " + position, Toast.LENGTH_SHORT).show();
}
});
This blog post by Hugo shows an alternative way without listeners: http://www.littlerobots.nl/blog/Handle-Android-RecyclerView-Clicks/
It comes down to adding these lines:
ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// do it
}
});
When using this class:
public class ItemClickSupport {
private final RecyclerView mRecyclerView;
private OnItemClickListener mOnItemClickListener;
private OnItemLongClickListener mOnItemLongClickListener;
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
mOnItemClickListener.onItemClicked(mRecyclerView, holder.getAdapterPosition(), v);
}
}
};
private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (mOnItemLongClickListener != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
return mOnItemLongClickListener.onItemLongClicked(mRecyclerView, holder.getAdapterPosition(), v);
}
return false;
}
};
private RecyclerView.OnChildAttachStateChangeListener mAttachListener
= new RecyclerView.OnChildAttachStateChangeListener() {
#Override
public void onChildViewAttachedToWindow(View view) {
if (mOnItemClickListener != null) {
view.setOnClickListener(mOnClickListener);
}
if (mOnItemLongClickListener != null) {
view.setOnLongClickListener(mOnLongClickListener);
}
}
#Override
public void onChildViewDetachedFromWindow(View view) {
}
};
private ItemClickSupport(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
mRecyclerView.setTag(R.id.item_click_support, this);
mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener);
}
public static ItemClickSupport addTo(RecyclerView view) {
ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
if (support == null) {
support = new ItemClickSupport(view);
}
return support;
}
public static ItemClickSupport removeFrom(RecyclerView view) {
ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
if (support != null) {
support.detach(view);
}
return support;
}
public ItemClickSupport setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
return this;
}
public ItemClickSupport setOnItemLongClickListener(OnItemLongClickListener listener) {
mOnItemLongClickListener = listener;
return this;
}
private void detach(RecyclerView view) {
view.removeOnChildAttachStateChangeListener(mAttachListener);
view.setTag(R.id.item_click_support, null);
}
public interface OnItemClickListener {
void onItemClicked(RecyclerView recyclerView, int position, View v);
}
public interface OnItemLongClickListener {
boolean onItemLongClicked(RecyclerView recyclerView, int position, View v);
}
}
And this value in ids.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="item_click_support" type="id" />
</resources>
This is my implementation of RecyclerAdapter.
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
ViewHolder.IOnClickListener clickListener;
ViewHolder.IOnLongClickListener longClickListener;
#Override
public void setClickListener(ViewHolder.IOnClickListener clickList, ViewHolder.IOnLongClickListener longClickListener) {
clickListener = clickList;
longClickListener = longClickListener;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_event, viewGroup, false);
return new ViewHolder(v, new ViewHolder.IOnClickListener() {
#Override
public void onLogo(View view, ViewHolder holder, int position) {
Log.d(TAG, "on logo click");
clickListener.onLogo();
}
#Override
public void onItem(View view, ViewHolder holder, final int position) {
Log.d(TAG, "on item click");
clickListener.onItem();
}
}, new ViewHolder.IOnLongClickListener() {
#Override
public void onItem(View view, ViewHolder holder, int position) {
Log.d(TAG, "on item long click");
longClickListener.onItem();
}
});
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, OnLongClickListener {
View mView;
ImageView mIcon;
IOnClickListener mClickListener;
IOnLongClickListener mLonglickListener;
public ViewHolder(View itemView,
IOnClickListener listener,
IOnLongClickListener longClickListener) {
super(itemView);
mView = itemView;
mIcon = (ImageView)itemView.findViewById(R.id.icon);
mClickListener = listener;
mLonglickListener = longClickListener;
mIcon.setOnClickListener(this);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
#Override
public void onClick(View v){
if(v instanceof ImageView){
mClickListener.onLogo(v, this, getAdapterPosition());
} else {
mClickListener.onItem(v, this, getAdapterPosition());
}
}
#Override
public boolean onLongClick(View v) {
mLonglickListener.onItem(v, this, getAdapterPosition());
return true;
}
public static interface IOnClickListener {
void onLogo(View view, ViewHolder v,int position);
void onItem(View view, ViewHolder v, int position);
}
public static interface IOnLongClickListener {
void onItem(View view, ViewHolder v,int position);
}
}
Then you can transfer your onClickListener to this.
RecyclerAdapter adapter = new RecyclerAdapter();
adapter.setClickListener(new ViewHolder.IOnClickListener(){...}, new ViewHolder.IOnLongClickListener(){...})
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onLongItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && mListener != null) {
mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
#Override
public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){}
}
and using:
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(parentView.getContext(),
recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
//here your logic
}
#Override
public void onLongItemClick(View view, int position) {
}
}));
Try this:
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(mActivity, mRecyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
Toast.makeText(mActivity, mProductList.get(position).getPname(), Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(mActivity, mProductList.get(position).getPname(), Toast.LENGTH_SHORT).show();
}
}));
public class RecyclerTouchListener implements
RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}

Categories

Resources