How to make multiple views in recyclerview item clickable? - android

I have this adapter class where I have an object with a list in it.
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Context context;
private Shop shop;
public ProductAdapter(Context context, Shop shop) {
this.context = context;
this.shop = shop;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.product_row, parent, false);
return new ProductViewHolder(v);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
holder.tvProductTitle.setText(shop.products.get(position).getTitle());
holder.tvProductDescription.setText(shop.products.get(position).getDescription());
Glide.with(context)
.load(shop.products.get(position).getImageUrl())
.placeholder(android.R.drawable.ic_menu_upload_you_tube)
.error(android.R.drawable.stat_notify_error)
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.into(holder.ivProduct);
}
#Override
public int getItemCount() {
if (shop.products != null) {
return shop.products.size();
}
return 0;
}
public static class ProductViewHolder extends RecyclerView.ViewHolder {
private TextView tvProductTitle, tvProductDescription;
private ImageView ivProduct;
public ProductViewHolder(View itemView) {
super(itemView);
tvProductTitle = (TextView) itemView.findViewById(R.id.tvProductTitle);
tvProductDescription = (TextView) itemView.findViewById(R.id.tvProductDescription);
ivProduct = (ImageView) itemView.findViewById(R.id.ivProduct);
}
}
public interface ClickListener {
void onClick(View v, int position);
void onLongClick(View v, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ProductAdapter.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ProductAdapter.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) {
}
}
I use this adapter in my fragment where I can click an item from the recyclerview which will open another activity with the selected product and it's parametars. Instead of clicking the whole item, I would like to click on part of it (lets say imageview) which will do the same as it is doing now. But, I would also like to put a checkbox in the recyclerview item itself which will have different function. At the moment, I can't use an intent in the adapter class. The way it is set up now I can only click the whole item. How can I make it work like I explained above?
public class ProductsFragment extends android.support.v4.app.Fragment {
private RecyclerView rvProduct;
private RecyclerView.LayoutManager layoutManager;
private ProductAdapter productAdapter;
public static ProductsFragment newInstance(Bundle args) {
ProductsFragment fragment = new ProductsFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_products, container, false);
rvProduct = (RecyclerView) v.findViewById(R.id.rvProduct);
rvProduct.setHasFixedSize(true);
layoutManager = new GridLayoutManager(getContext(), 2);
rvProduct.setLayoutManager(layoutManager);
Bundle bundle = getArguments();
final Shop shop = (Shop) bundle.getSerializable("shop");
productAdapter = new ProductAdapter(getContext(), shop);
rvProduct.setAdapter(productAdapter);
productAdapter.notifyDataSetChanged();
rvProduct.addOnItemTouchListener(new ProductAdapter.RecyclerTouchListener(getContext(), rvProduct, new ProductAdapter.ClickListener() {
#Override
public void onClick(View v, int position) {
Intent details = new Intent(getContext(), ProductDetailsActivity.class);
details.putExtra("product", shop.products.get(position));
startActivity(details);
}
#Override
public void onLongClick(View v, int position) {
}
}));
return v;
}
}
EDIT:
I've managed to do this, please tell me if this is right and efficient way:
holder.tvProductTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ProductDetailsActivity.class);
i.putExtra("product", shop.products.get(position));
context.startActivity(i);
}
});

The way you doing it is not correct.
As your onBindViewHolder will be called repeatedly as you scroll through the list, every time a new listener will be set.
Instead you should set the listeners in the ViewHolder class of Adapter. And use getAdapterPosition() method to get the position of item clicked.
For example:
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Context context; private Shop shop;
public ProductAdapter(Context context, Shop shop) {
this.context = context;
this.shop = shop;
}
#Override public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.product_row, parent, false);
return new ProductViewHolder(v);
}
#Override public void onBindViewHolder(ProductViewHolder holder, int position) {
holder.tvProductTitle.setText(shop.products.get(position).getTitle());
holder.tvProductDescription.setText(shop.products.get(position).getDescription());
Glide.with(context) .load(shop.products.get(position).getImageUrl()) .placeholder(android.R.drawable.ic_menu_upload_you_tube) .error(android.R.drawable.stat_notify_error) .diskCacheStrategy(DiskCacheStrategy.RESULT) .into(holder.ivProduct);
}
#Override public int getItemCount()
{
if (shop.products != null) {
return shop.products.size();
} return 0;
}
public static class ProductViewHolder extends RecyclerView.ViewHolder {
private TextView tvProductTitle, tvProductDescription;
private ImageView ivProduct;
public ProductViewHolder(View itemView)
{
super(itemView);
tvProductTitle = (TextView) itemView.findViewById(R.id.tvProductTitle);
tvProductDescription = (TextView) itemView.findViewById(R.id.tvProductDescription);
ivProduct = (ImageView) itemView.findViewById(R.id.ivProduct);
// Set onclickListener on image
ivProduct.setOnCliCkListener(new onClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(context, ProductDetailsActivity.class);
i.putExtra("product",
shop.products.get(getAdapterPosition()));
context.startActivity(i);
}
}
}
}
public interface ClickListener {
void onClick(View v, int position);
void onLongClick(View v, int position);
}
}

You can add click listeners to each respective view of the inflated item in public onBindViewHolder. Did you consider that?
Edit: Ok it's what you did. I don't know about the efficiency though, but this is the way I would do it.

Related

Android RecyclreView OnCLick Listener

Error on android recyclerView Adapter. App will stop working while click on RecyclerView items. I want to go other activity when click any items, when i'm using Toast it working fine but if i add Intent then it stop working.
Here is my Interface :
public interface OnItemClickListener {
void onClick(View view, int position);
}
here is my recycler Adapter calss :
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> {
private List<Items> items;
private Context context;
public RecAdapter(List<Items> items, Context context )
{
this.items = items;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.countryname.setText(items.get(position).getCountryname());
holder.rank.setText(items.get(position).getRank());
Picasso.with(context)
.load(items.get(position).getFlag())
.into(holder.flag);
holder.setClickListener(new OnItemClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return items.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView countryname, rank;
ImageView flag;
private OnItemClickListener clickListener;
public MyViewHolder(View itemView) {
super(itemView);
countryname = (TextView) itemView.findViewById(R.id.capital);
rank = (TextView) itemView.findViewById(R.id.rank);
flag = (ImageView) itemView.findViewById(R.id.flag);
itemView.setTag(itemView);
itemView.setOnClickListener(this);
}
public void setClickListener(OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
Add click listener like this:-
View itemView;
Context context;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
this.context=parent.getContext();
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
}
copying an answer of mine from a different question:
as you already know this method is no longer available in the RecyclerView class.
My approach towards implementing onClick events in a RecyclerView is something like this:
class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
interface OnClickListener {
void onClick(Item item);
}
private final List<Item> dataset;
private final OnClickListener l;
public MyAdapter(List<Item> data, OnClickListener listener) {
this.dataset = data;
this.l = listener;
}
#Override MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = //inflate layout
MyClick click = new MyClick() {
onClick(int position) {
if (l != null) {
l.onClick(dataset.get(position));
}
}
};
return new MyViewHolder(click, v);
}
static class MyViewHolder {
final MyClick l;
public MyViewHolder(MyClick listener, View view) {
super(view);
l = listener;
// inflate views
view.setOnClickListener(new OnClickListener() {
if (l != null) {
l.onClick(getAdapterPosition());
}
});
}
interface MyClick {
void onClick(int position);
}
}
}
class MyActivity extends AppCompatActivity {
#Override void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout
MyAdapter adapter = new MyAdapter(getData(), new OnClickListener() {
#Override onClick(Item item) {
// do stuff with item
}
});
}
}
You can not click an holder directly..... give a id to the view then re write the code as below:
holder.(someitem).setClickListener(new OnItemClickListener() {//you need a view to execute the onclicklistener
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
Here is code which i create click listener for Recycler Item Click
Using this you will get two types of click
Simple Item click.
Item Long click.
Here is RecyclerItemClickListener.java File
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener
{
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private 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 childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null)
{
mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
}
}
});
}
#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.getChildPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
How to use in Activity and Fragment
rvcyclerView.addOnItemTouchListener(new RecyclerItemClickListener(context, rvcyclerView,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
//do you what you want tot do simple click
}
#Override
public void onItemLongClick(View view, int position) {
//do you what you want tot do on long click
}
}));
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> implements View.OnClickListener {
private List<Items> items;
private Context context;
private OnItemClickListener clickListener;
public RecAdapter(List<Items> items, Context context )
{
this.items = items;
this.context = context;
}
public void setClickListener(OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.countryname.setText(items.get(position).getCountryname());
holder.rank.setText(items.get(position).getRank());
Picasso.with(context)
.load(items.get(position).getFlag())
.into(holder.flag);
holder.flag.setOnClickListener(this);
}
#Override
public int getItemCount() {
return items.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView countryname, rank;
ImageView flag;
public MyViewHolder(View itemView) {
super(itemView);
countryname = (TextView) itemView.findViewById(R.id.capital);
rank = (TextView) itemView.findViewById(R.id.rank);
flag = (ImageView) itemView.findViewById(R.id.flag);
}
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
On Your Activity / Fragment Implement OnItemClickListener
public class MainActivity extends AppCompatActivity implements OnItemClickListener{
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayoutManager layout = new
LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layout );
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
RecAdapter adapter = new RecAdapter(items ,getContext());
adapter.setClickListener(this);
mRecyclerView.setAdapter(adapter );
}
#Override
public void onClick(View view, int position) {
switch(view.getId()) {
}
}
}

How to take textview data from recycler view to another activity?

I want to take textview data from recycler view to another activity.I want to take
workshop_name TextView to Otheractivity.
Here is my code.
MechSearchActivity.java
public class MechSearchActivity extends AppCompatActivity {
List<SearchResponse.WorkshopDataBean> workshopList;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_mec);
recyclerView = (RecyclerView) findViewById(R.id.rv_workshoplist);
callSearchApi();
onItemClick();
}
public void callSearchApi() {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<SearchResponse> call = apiService.getSearchData( "workshop_name","image", "street", "locality", "city"); // single search for all the values
call.enqueue(new Callback<SearchResponse>() {
#Override
public void onResponse(Call<SearchResponse> call, retrofit2.Response<SearchResponse> response) {
SearchResponse searchResponse = response.body();
workshopList = searchResponse.getWorkshopData();
MechanicRecyclerAdapter adapter = new MechanicRecyclerAdapter(MechSearchActivity.this, workshopList);
recyclerView.setAdapter(adapter);
LinearLayoutManager mGridLayoutManager = new LinearLayoutManager(MechSearchActivity.this); // (Context context, int spanCount)
recyclerView.setLayoutManager(mGridLayoutManager);
}
#Override
public void onFailure(Call<SearchResponse> call, Throwable t) {
}
});
}
private void onItemClick() {
final GestureDetector mGestureDetector = new GestureDetector(MechSearchActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
recyclerView_ws.addOnItemTouchListener(new
RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildPosition(child);
String workshop_name = workshopList.get(position).getWorkshop_name();
Intent intent = new Intent(MechSearchActivity.this, OtherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("workshop_name", workshop_name);
startActivity(intent);
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
}
MechRecyclerAdapter.java
public class MechanicRecyclerAdapter extends RecyclerView.Adapter<MechanicRecyclerAdapter.MyViewHolder> {
private static final String TAG = MechanicRecyclerAdapter.class.getSimpleName();
Context mContext;
private LayoutInflater inflater;
String vehicle_type;
List<SearchResponse.WorkshopDataBean> workshopList;
public MechanicRecyclerAdapter(Context context, List<SearchResponse.WorkshopDataBean> workshopList) {
inflater = LayoutInflater.from(context);
this.workshopList = workshopList;
mContext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_workshop, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
SearchResponse.WorkshopDataBean current = workshopList.get(position);
String ws_name = workshopList.get(position).getWorkshop_name();
holder.tv_workshopname.setText(ws_name);
}
#Override
public int getItemCount() {
return workshopList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
SearchResponse.WorkshopDataBean current;
TextView tv_workshopname;
public MyViewHolder(View itemView) {
super(itemView);
tv_workshopname = (TextView) itemView.findViewById(workshop_name);
}
}
}
OtherActivity.java
public class OtherActivity extends AppCompatActivity {
TextView SingleWorkshopName;
String workshop_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.otheractivity);
SingleWorkshopName=(TextView)findViewById(R.id.single_workshop_name);
Bundle extras = getIntent().getExtras();
workshop_name = extras.getString("workshop_name", null);
}
}
For that you need to create one interface in your MechanicRecyclerAdapter
public interface OnListItemClick {
void onItemClick(int position);
}
in onBindViewHolder() assign your click by using following code
viewHolder.main_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onListItemClick.onItemClick(position);
}
});
Implements this interface in you MechSearchActivity you will get onItemClick() method in your activity using position you will get proper name of row and pass to other activity using intent.putExtra("workshop_name", workshop_name);

RecyclerView and Admob Items: Problems with onClickListener

I've added a NativeExpressAdView inside my RecyclerView ItemList but now the onClickListener is interfering with the NativeExpressAdView. My "normal" Items consist of text and one larger Image. When the larger Image gets clicked on, a DialogFragment gets opened and shows detailed information of the Item. However, the NativeExpressAdView shouldn't run into this onClickListener. The App keeps crashing because it tries to open the not existing detailed View of the NativeExpressAdView ...
MainActivity
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
......
recyclerView.addOnItemTouchListener(new ItemAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new ItemAdapter.ClickListener() {
#Override
public void onClick(View view, final int position) {
final Bundle bundle = new Bundle();
bundle.putSerializable("events", events);
bundle.putInt("position", position);
final Event event = events.get(position);
detailView = (ImageView) view.findViewById(R.id.item_thumbnail);
detailView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.setCancelable(true);
newFragment.show(ft, "slideshow");
}
});
....
some other button onClickListener()...
....
}
#Override
public void onLongClick(View view, int position) {
}
}));
ItemAdapter
public class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private List<Event> events;
private Context mContext;
public ItemAdapter(Context context, List<Event> events){
mContext = context;
this.events = events;
}
public static class MyViewHolder extends RecyclerView.ViewHolder{ // implements View.OnClickListener {
public ImageView thumbnail;
public TextView event_name;
public TextView event_date;
public TextView event_descr;
public TextView event_attending;
public TextView event_maybe;
public MyViewHolder(android.view.View view){
super(view);
thumbnail = (ImageView) view.findViewById(R.id.item_thumbnail);
event_name = (TextView) view.findViewById(R.id.tV_event_name);
event_date = (TextView) view.findViewById(R.id.tV_event_date);
event_descr = (TextView) view.findViewById(R.id.tV_event_descr);
event_attending = (TextView) view.findViewById(R.id.tV_attending_count);
event_maybe = (TextView) view.findViewById(R.id.tV_maybe_count);
}
}
public static class ViewHolderAdMob extends RecyclerView.ViewHolder {
public NativeExpressAdView nativeExpressAdView;
public ViewHolderAdMob(View view) {
super(view);
nativeExpressAdView = (NativeExpressAdView) view.findViewById(R.id.ad_nativeAdOne);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("228****************************")
.build();
nativeExpressAdView.loadAd(adRequest);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
//View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_items, parent, false);
switch (viewType){
case 1:{
View itemView = inflater.inflate(R.layout.rv_items, parent, false);
viewHolder = new MyViewHolder(itemView);
break;
}
case 2:{
View itemView = inflater.inflate(R.layout.native_ad_one, parent, false);
viewHolder = new ViewHolderAdMob(itemView);
break;
}
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position){
Event event = events.get(position);
switch (holder.getItemViewType()){
case 1:{
MyViewHolder viewHolder = (MyViewHolder) holder;
viewHolder.event_name.setText(event.getEventName());
viewHolder.event_date.setText(event.getEventDate());
viewHolder.event_descr.setText(event.getEventDescription());
viewHolder.event_attending.setText(event.getEventAttending());
viewHolder.event_maybe.setText(event.getEventMaybeComming());
Glide.with(mContext).load(event.getEventImage())
.thumbnail(0.9f)
.crossFade()
//.diskCacheStrategy(DiskCacheStrategy.ALL)
.fitCenter()
.into(viewHolder.thumbnail);
break;
}
case 2:{
break;
}
}
}
#Override
public int getItemCount(){
return events.size();
}
#Override
public int getItemViewType(int position) {
return events.get(position).getViewType();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ItemAdapter.ClickListener clickListener;
public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ItemAdapter.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){
}
}
}
I kind of see where the problem stems from, since the the RecyclerView is listening for input and naturally reacts to it but I kind of thought that by defining inside my MainActivity that detailView = (ImageView) view.findViewById(R.id.item_thumbnail); it will only react to "normal" items since R.id.item_thumbnail is an element of my "normal" items xml whereas the NativeExpressAdView doesn't have such an element. How can I fix this problem and get the proper functionality ??
Set the click listener in onBindViewHolder, in your adapter, depending on the view type.
public static class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final MyListClickListener clickListener;
public ItemAdapter(MyListClickListener clickListener) {
this.clickListener = clickListener;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == ADVERT_VIEW_TYPE) {
// do whatever you do for adverts
} else {
// do what you do for items and set the click listener
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
clickListener.onShowDetailViewClicked(); // pass the parameters you need to identify this particular item
}
});
}
}
public interface MyListClickListener {
void onShowDetailViewClicked();
}
}
You are setting the onItemTouchListener{...} to the entire RecyclerView. It assumes that no matter where you touch, there is the detail view. But you have different types of rows in your RecyclerView. The best option would be to add touch listeners to each individual item in your ViewHolder classes.

onClickListener in RecyclerView adapter?

I want to set up an onClickListener within my RecyclerView adapter so I can easily refer to the other views to retrieve their tags.
Is it possible to set up an onClickListener in a RecyclerView adapter? How would I do it? Would it affect performance?
Here is my RecyclerView adapter:
public class PostRecyclerAdapter extends RecyclerView.Adapter<PostRecyclerAdapter.ViewHolder> {
private Context context;
private List<Post> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public LinearLayout mainLayout;
public TextView username;
public ImageView image;
public ViewHolder(LinearLayout view) {
super(view);
view.setOnCreateContextMenuListener(this);
mainLayout = (LinearLayout) view.findViewById(R.id.main_view);
username = (TextView) view.findViewById(R.id.username);
image = (ImageView) view.findViewById(R.id.image);
}
}
public PostRecyclerAdapter(Context context, List<Post> myDataset) {
this.context = context;
this.mDataset = myDataset;
}
#Override
public PostRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_layout, parent, false);
ViewHolder vh = new ViewHolder((LinearLayout) view);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Post postItem = mDataset.get(position);
holder.username.setText(postItem.getUserame());
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
I would like to suggest a much simpler approach than the one given above.
in your adapter you would have written static view holder class right for that add the following code
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
// your views declared here
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
// your view initialised here
cardView=itemView.findViewById(R.id.card_view);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.card_view:
// your logic
break;
}
}
}
by doing so you can handle individual click of your layout as well as the entire layout click
You can use GestureDetector for this. This is very simple to use :
Create A class RecyclerTouchListener :
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.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);
}
}
and you can use this class as follow :
rvFilterOptions = (RecyclerView) rootView.findViewById(R.id.rvCommon);
rvFilterOptions.setHasFixedSize(true);
rvFilterOptions.addItemDecoration(new DividerItemDecoration(getActivity(),
DividerItemDecoration.VERTICAL_LIST));
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
rvFilterOptions.setLayoutManager(mLayoutManager);
rvFilterOptions.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), rvFilterOptions, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
// Perform click operation and you can get post item from array using position
}
#Override
public void onLongClick(View view, int position) {
// Perform Long click operation
}
}));
Note : Concept is taken from LINK
This is simplest implementation but this will be inside recyclerviews adapter. If you want to get row item clicklistener in activity then use Interface.
public class PostRecyclerAdapter extends RecyclerView.Adapter<PostRecyclerAdapter.ViewHolder> {
private Context context;
private List<Post> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public LinearLayout mainLayout;
public TextView username;
public ImageView image;
public View mRowItem;
public ViewHolder(LinearLayout view) {
super(view);
view.setOnCreateContextMenuListener(this);
mRowItem = view;
mainLayout = (LinearLayout) view.findViewById(R.id.main_view);
username = (TextView) view.findViewById(R.id.username);
image = (ImageView) view.findViewById(R.id.image);
}
}
public PostRecyclerAdapter(Context context, List<Post> myDataset) {
this.context = context;
this.mDataset = myDataset;
}
#Override
public PostRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_layout, parent, false);
ViewHolder vh = new ViewHolder((LinearLayout) view);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Post postItem = mDataset.get(position);
holder.username.setText(postItem.getUserame());
//Whole row item
holder.mRowItem.setTag(position);
holder.mRowItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = (int) v.getTag();
// handle your row item click.
}
});
}
#Override
public int getItemCount() {
return mDataset.size();
}
}

RecyclerView onItemClick Listener

How to implement RecyclerView onItemClick listener as we do with ListView, this is my old Adapter class using ListView:
public class GenreAdapter extends BaseAdapter {
....
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.textTitle = (TextView) v.findViewById(R.id.textTitle);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.textTitle.setText(genreArrayList.get(position).getTitle());
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putSerializable("data", genreArrayList);
bundle.putInt("current", position);
Intent intent = new Intent(context, MovieActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtras(bundle);
context.startActivity(intent);
}
});
return v;
}
static class ViewHolder {
public TextView textTitle;
}
MainFragment.java:-
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_main, container, false);
/* Initialize recycler view */
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
list = new ArrayList<MainPoho>();
adapter = new MainAdapter(getActivity(), list);
mRecyclerView.setAdapter(adapter);
.......
}
And here is my new Adapter class using RecyclerView :
public class MyRecyclerAdapter extends RecyclerView.Adapter<FeedListRowHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public FeedListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
FeedListRowHolder mh = new FeedListRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(FeedListRowHolder feedListRowHolder, int i) {
FeedItem feedItem = feedItemList.get(i);
feedListRowHolder.title.setText(Html.fromHtml(feedItem.getTitle()));
}
#Override
public int getItemCount() {
if(feedItemList !=null){
return feedItemList.size();
} else {
return 0;
}
}
public class FeedListRowHolder extends RecyclerView.ViewHolder {
protected TextView title;
public FeedListRowHolder(View view) {
super(view);
this.title = (TextView) view.findViewById(R.id.title);
}
FeedItem.java:-
public class FeedItem {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
first store whole view in your viewHolder:
public class FeedListRowHolder extends RecyclerView.ViewHolder {
protected TextView title;
protected View mRootView;
public FeedListRowHolder(View view) {
super(view);
this.title = (TextView) view.findViewById(R.id.title);
mRootView = view;
}
then set click listener at onBindViewHolder:
#Override
public void onBindViewHolder(FeedListRowHolder feedListRowHolder, int i) {
FeedItem feedItem = feedItemList.get(i);
feedListRowHolder.title.setText(Html.fromHtml(feedItem.getTitle()));
feedListRowHolder.mRootView.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
First you have to implement your own OnItemTouchListener :
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector gestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
gestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
//here get the view that has been touched
View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
//now pass the item and its position to your click listener
if(child!=null && clickListener!=null){
clickListener.onClick(child, recyclerView.getChildPosition(child));
}
return true;
}
#Override
public void onLongPress(MotionEvent e) {
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
//use the gesture detector to intercept singletap and longtouch events
gestureDetector.onTouchEvent(motionEvent);
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
}
And then you will have to implement the ClickListener that will be called by the RecyclerTouchListener above :
private RecyclerTouchListener.ClickListener mClickListener = new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
//Do something with your item...
mRecyclerAdapter.getElementAt(position).doSomething();
}
}
I know its a little late but for all those who wander and are not lost. I found this elegant solution here.
So basically you create a ItemClickSupport class like below
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 then in your activity/fragment where you have defined and bind your recyclerView just do the following
//Here the mRecyclerView is the name of the defined recyclerView
ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// do it
}
});
Also, you need to create an ids.xml file inside your res/values folder and define the following inside
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="item_click_support" type="id" />
</resources>
I hope this helps. Still recommend you to go through the article to read more regarding it.

Categories

Resources