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

时间:2019-07-09 17:54:54

标签: java android firebase-realtime-database android-alertdialog recycler-adapter

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

我可以轻松地在扩展AppCompatActivity的常规活动类中创建警报对话框生成器,而在Adapter类中则不能。为什么?

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

1 个答案:

答案 0 :(得分:2)

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

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

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