【问题标题】:How can i create an Alert Dialog Builder in a RecyclerView.Adapter class如何在 RecyclerView.Adapter 类中创建警报对话框生成器
【发布时间】:2020-05-09 13:35:42
【问题描述】:

我的 RecylerView.Adapater 类中的 HoAlertDialogBu​​ilder 收到一条错误消息,提示“在 Builder 中无法访问 com.example.john.atsnotify.Adapter.PupilGroupAdapter 类”

我可以在常规活动类中轻松创建警报对话框生成器,该活动类扩展 AppCompatActivity 但不在适配器类中。为什么?

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

【问题讨论】:

    标签: java android firebase-realtime-database android-alertdialog android-recyclerview


    【解决方案1】:

    构造函数的参数(您当前为其传递PupilGroupAdapter.this)必须是Context 类型。您的适配器不是上下文,所以这失败了。

    您可以通过getContext() 方法从任何View 实例中检索上下文。在您的情况下,您试图通过单击按钮显示警报对话框,因此您可以使用传递给单击侦听器的视图上下文:

    @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
    }
    

    【讨论】:

      【解决方案2】:

      正在寻找类似的方法,但 Context 没有帮助。通过https://chat.stackoverflow.com/rooms/110530/discussion-between-sukhbir-and-amir-p的聊天记录找到解决方案

      使用 Adapter 构造函数参数在我的代码中实现它,如下所示:

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

      在我的活动类中启动回收器适配器:

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

      RecyclerAdapter onBindViewHolder 类中的警告对话框:

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

      【讨论】:

        猜你喜欢
        • 2017-07-21
        • 1970-01-01
        • 2014-04-12
        • 1970-01-01
        • 1970-01-01
        • 2018-01-23
        • 1970-01-01
        • 2018-01-10
        • 2012-09-15
        相关资源
        最近更新 更多