在RecyclerView Adapter类的ViewHolder中显示AlertDialog

时间:2015-10-30 13:43:28

标签: android alertdialog android-viewholder

我已经实现了一些带有一些行的RecyclerView,而我现在尝试使用AlertDialog在用户点击一行时显示一条消息。

我已成功在适配器中实现了setOnClickListener,但我无法使AlertDialog正常工作,系统一直告诉我,我无法在ViewHolder中使用AlertDialog.Builder:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

我的GitHub代码为here

public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView textView;

    public ViewHolder(View itemView) {
        super(itemView);
        textView = (TextView) itemView;
        itemView.setOnClickListener(this);
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle(null);
        {
            alertDialogBuilder
                    .setMessage("You selected ")
                    .setCancelable(true); // True allows you to use the back button to exit the dialog, false does not
        }
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

2 个答案:

答案 0 :(得分:5)

今天结束了与丈夫的重构,更新的代码为here

我们创建了一个接口并在main活动中实现了它,然后我们从itemView上设置的View.OnClickListener调用此接口中的方法。

我们向ViewHolder添加了一个点击监听器:

https://github.com/lararufflecoles/RecyclerView100/blob/master/app/src/main/java/es/rufflecol/lara/recyclerview100/RecyclerAdapter.java#L69

然后将Activity设为监听器:

https://github.com/lararufflecoles/RecyclerView100/blob/master/app/src/main/java/es/rufflecol/lara/recyclerview100/MainActivity.java#L42

希望这个问题可能在将来帮助其他人。

答案 1 :(得分:-2)

只需使用

http://yourdomainname.com/index.php?option=com_contact&view=contact&id=100

您的问题将得到解决。