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

Ayomide Ajayi :

HoAlertDialogBuilder in my RecylerView.Adapater class i get an error saying "in Builder cannot to the com.example.john.atsnotify.Adapter.PupilGroupAdapter class"

i can easily create an alert dialog Builder in a regular activity class which extends AppCompatActivity but not in an Adapter class. why?

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

Ben P. :

The argument to the constructor (for which you are currently passing PupilGroupAdapter.this) must be of type Context. Your adapter is not a Context, so this is failing.

You can retrieve a context from any View instance via the getContext() method. 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
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=133366&siteId=1