问题描述
我已经实现了RecyclerView.现在,当单击RecyclerView项时,我想显示一个AlertDialog.我尝试了许多方法,但没有一个起作用.这是我的适配器类,
I have implemented a RecyclerView. Now I want to display an AlertDialog when an item of RecyclerView is clicked. I tried many ways and none of them worked.Here is my adapter class,
public class SearchResultAdapter extends RecyclerView.Adapter<SearchResultAdapter.MyViewHolder> {
private List<Searchresult> resultList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView item1, item2, item3;
public MyViewHolder(View view) {
super(view);
item1 = (TextView) view.findViewById(R.id.item1);
item2 = (TextView) view.findViewById(R.id.item2);
item3 = (TextView) view.findViewById(R.id.item3);
}
}
public SearchResultAdapter(List<Searchresult> resultList) {
this.resultList = resultList;
}
@Override
public MyViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.search_result_row, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
Searchresult result = resultList.get(position);
holder.item1.setText(result.getItem1());
holder.item2.setText(result.getItem2());
holder.item3.setText(result.getItem3());
}
@Override
public int getItemCount() {
return resultList.size();
}
}
AlertDialog应该显示item1,item2和item3.请帮助我在RecyclerView上实现onClickListener.
The AlertDialog should display item1,item2 and item3.Please help me to implement an onClickListener on RecyclerView.
推荐答案
问题在这里,您还必须将context
传递给适配器构造函数,如下所示
problem is here , you have to also pass context
to the adapter constructor like given below
public SearchResultAdapter(List<Searchresult> resultList , Context context) {
this.resultList = resultList;
this.context = context
}
在活动"中启动适配器的使用,如下所示:
in your Activity where you initiate adapter use like below
SearchResultAdapter madapter = new SearchResultAdapter (List, this);
然后在您的onBindViewHolder中
then in your onBindViewHolder
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
Searchresult result = resultList.get(position);
holder.item1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//pass the 'context' here
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Your title");
alertDialog.setMessage("your message ");
alertDialog.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setNegativeButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// DO SOMETHING HERE
}
});
AlertDialog dialog = alertDialog.create();
dialog.show();
}
});
}
这篇关于Android | RecyclerView项目上的AlertDialog请点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!