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;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…