I created a basic Class called ListItem, which just stores two Strings and an integer.
This is my container for items that sit in a RecyclerView.
I tried to make ListItems clickable, so I made the ListItem extend the View class. And then added an OnClickListener and set it. It hasn't worked. I tested by creating a short message using TOAST but nothing displays. Does anyone have any idea why?
ListItem class:
public ListItem(String title, String date, int url, Context context, AttributeSet attrs){
super(context, attrs);
this.title = title;
this.date = date;
this.url = url;
}
...class where ListItems are created.....
private AttributeSet attrs;
ListItem y = new ListItem(title, date, a, this.getContext(), attrs);
View.OnClickListener mFan = new View.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getActivity(), "TEST" , Toast.LENGTH_SHORT).show();
}
};
y.setOnClickListener(mFan);
There is a method for this in the View class.
y.setClickable(true);
You may also need to do this for the ListView as well.
myListView.setClickable(true);
Implementing item click listener in RecyclerView is a bit different.
I assume you have implemented your own custom RecyclerViewAdpater which should be like this. You have to implement your own OnClickListener interface inside it.
public class CustomRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ListItem> listItems;
private static OnListItemClickListener onListItemClickListener;
public interface OnListItemClickListener {
public void onListItemClick(int position, View v);
}
public void setOnListItemClickListener(OnListItemClickListener onListItemClickListener) {
this.onListItemClickListener = onListItemClickListener;
}
// You implement OnClickListener in your list item view holder.
public static class ListItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ListItemViewHolder(View listItemView) {
super(listItemView);
listItemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
onListItemClickListener.onListItemClick(getAdapterPosition(), view);
}
}
}
Then in your main activity or fragment you would do something like this.
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
CustomRecyclerViewAdapter customRecyclerViewAdapter = new CustomRecyclerViewAdapter(listItems);
recyclerView.setAdapter(customRecyclerViewAdapter);
customRecyclerViewAdapter.setOnListItemClickListener(new CustomRecyclerViewAdapter.OnListItemClickListener() {
@Override
public void onListItemClick(int position, View v) {
Toast.makeText(getActivity(), "TEST" , Toast.LENGTH_SHORT).show();
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.