简体   繁体   English

如何在 RecyclerView.Adapter 类中创建警报对话框构建器

[英]How can i create an Alert Dialog Builder in a RecyclerView.Adapter class

HoAlertDialogBuilder in my RecylerView.Adapater class i get an error saying "in Builder cannot to the com.example.john.atsnotify.Adapter.PupilGroupAdapter class" HoAlertDialogBu​​ilder 在我的 RecylerView.Adapater 类中,我收到一条错误消息“在 Builder 中不能到 com.example.john.atsnotify.Adapter.PupilGroupAdapter 类”

i can easily create an alert dialog Builder in a regular activity class which extends AppCompatActivity but not in an Adapter class.我可以轻松地在扩展 AppCompatActivity 但不在适配器类中的常规活动类中创建警报对话框生成器。 why?为什么?

https://pastebin.com/WqXCG1Ch AlertDialog.Builder builder = new AlertDialog.Builder(PupilGroupAdapter.this); https://pastebin.com/WqXCG1Ch AlertDialog.Builder builder = new AlertDialog.Builder(PupilGroupAdapter.this);

The argument to the constructor (for which you are currently passing PupilGroupAdapter.this ) must be of type Context .构造函数的参数(您当前PupilGroupAdapter.this传递PupilGroupAdapter.this )必须是Context类型。 Your adapter is not a Context, so this is failing.您的适配器不是上下文,因此这是失败的。

You can retrieve a context from any View instance via the getContext() method.您可以通过getContext()方法从任何View实例中检索上下文。 In your case, you're trying to show the alert dialog from a button click, so you can use the context of the view passed to the click listener:在您的情况下,您试图通过单击按钮显示警报对话框,因此您可以使用传递给单击侦听器的视图上下文:

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
    // ...

    viewHolder.btnAdd.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showAlertDialog(view.getContext()); // pass the context here
        }
    } );
}

private void showAlertDialog(Context context) { // receive the context here
    AlertDialog.Builder builder = new AlertDialog.Builder(context); // use the context here
}

Was looking for a similar way and Context did not help.正在寻找类似的方式,而 Context 没有帮助。 Found a solution through chat history of https://chat.stackoverflow.com/rooms/110530/discussion-between-sukhbir-and-amir-p通过https://chat.stackoverflow.com/rooms/110530/discussion-between-sukhbir-and-amir-p的聊天记录找到解决方案

Implemented it in my code with Adapter constructor parameter like so:在我的代码中使用 Adapter 构造函数参数实现它,如下所示:

public AdapterClass(..., Activity abc, ...){
  this.abc = abc;
}

In my activity class initiating the recycler adapter:在我启动回收器适配器的活动类中:

AdapterClass newAdapter = new AdapterClass(..., CurrentActivity.this, ...);

And alert dialog in RecyclerAdapter onBindViewHolder class:RecyclerAdapter onBindViewHolder类中的警报对话框:

public void startAlert(..., Activity passedActivity, ...){
  AlertDialog.Builder aB = new AlertDialog.Builder(passedActivity);
  ...
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM