列表视图中的对话框 android

Dialog in list view android

我有一个包含元素的listview和一个删除按钮,当我点击这个按钮时我想显示一个dialog然后确认是否删除元素,问题是我无法在 listview 上显示对话框,我遇到了上下文问题。

public void onClick(View v) {
    if(v.getId()==R.id.Supprimer){
        AlertDialog.Builder builder = new 
        AlertDialog.Builder(getContext());

        builder.setCancelable(true);
        builder.setTitle("Suppression d'un rendez-vous");
        builder.setMessage("Voulez vous supprimer ce rendez-vous");

        builder.setNegativeButton("Non", new 
        DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });

        builder.setPositiveButton("Oui", new 
        DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //alertTextView.setVisibility(View.VISIBLE);
                GestBDD.suppRDV(rdv,getContext());
                adapter.remove(getPosition(rdv));
                cl.notifyDataSetChanged();
                Toast.makeText(getContext(),"Rendez vous 
                supprimé",Toast.LENGTH_LONG).show();
            }
        });
        builder.show();

        }
        }

错误在 builder.show() 行,它说

     W/System.err:     at 
     com.example.hp.bendaoudtest.RDVAdapter.onClick(RDVAdapter.java:110)

使用

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

AlertDialog dialog = builder.create();
dialog.show();

而不是 builder.show(); 以获取更多信息 https://developer.android.com/guide/topics/ui/dialogs.html

A​​lertDialog 只接受 activity context 而不是 application context。如果您的 getContext() 获得 应用程序上下文 ,您将收到一个错误。您的 getContext() 方法应该 return activity context 可以从您正在使用的 activity class 实例化,方法是发送 this 作为构造函数参数。不要将 getApplicationContext() 作为构造函数参数发送。示例:

RVDAdapter rvdadapter = new RVDAdapter(this);