简体   繁体   English

如何在Adapter类中使用AlertDialog?

[英]How can I use AlertDialog in an Adapter class?

I have send the Context to the Adapter 我已将上下文发送到适配器

public ImageAdapter(Context context, List<Image> imagesList) {
        this.context = context;
        mImageList = imagesList;
    }

And I use AlertDialog this way: 我以这种方式使用AlertDialog:

AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AlertDialogCustom);

But I got error: 但是我得到了错误:

Unable to add window -- token null is not valid; is your activity running?

从Activity / fragment相应地将上下文作为ActivityName.this / getActivity()发送到调用适配器的位置

To do that you need to define call back. 为此,您需要定义回叫。

  • define interface(callback with method ) 定义接口(带方法的回调)
  • implement this call back in activity that holds adapter 在保存适配器的活动中实施此回调
  • define object as parameter for your adapter like 将对象定义为适配器的参数,例如

    public ImageAdapter(Context context, List imagesList, Callback callback) { this.context = context; public ImageAdapter(Context context,List imagesList,Callback callback){this.context = context; mImageList = imagesList; mImageList = imagesList; this.callback =callback; this.callback =回调 } }

  • inside your adapter call method inside your call back as you want your activity will listen to this action and inside this method in your activity you can create your alert dialog 在适配器调用方法内部,在您希望的活动中回叫,您的活动将监听此操作,在活动中的此方法内部,您可以创建警报对话框

您应该将Activity而不是Context传递给AlertDialog.Builder。的构造函数,并且必须确保在对话框运行时该活动正在运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在回收站适配器类中使用getcontext()? - How can I use getcontext() in recycler adapter class? 如何与AlertDialog内的Adapter中的Adapter中的Fragment内的AlertDialog View交互? - How do I interact with the AlertDialog View that is inside a Fragment from an Adapter inside an Adapter inside the AlertDialog? 如何更改 Adapter 类中的 itemLayout - How can i change the itemLayout in Adapter class 如何在 Adapter 类中使用我的全局变量? 安卓 - How can I use my global variable inside an Adapter class? Android 如何在列表适配器上显示AlertDialog - How to display AlertDialog on List Adapter 我可以自动连接适配器类吗? - Can I Autowire an Adapter Class? 如何在另一个类适配器中访问给定适配器的 onBindViewHolder 项? - How can I access onBindViewHolder items of a given adapter in another class adapter? 如何在警报对话框中保存多项选择 state? - how can i save the multichoice state in an alertdialog? 如何将 AlertDialog 标题居中? - How can I center my AlertDialog Title? 如何在不同的活动上使用GridView的同一适配器 - How Can I use Same Adapter of a GridView on Different activities
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM