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();
}
});
}
and using:
This is my implementation of RecyclerAdapter.
Then you can transfer your onClickListener to this.
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(); }
public class RecyclerTouchListener implements
RecyclerView.OnItemTouchListener {
}
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:
When using this class:
And this value in ids.xml: