繁体   English   中英

在ListView中单击按钮时无法显示AlertDialog

[英]Unable to show AlertDialog on button click in a ListView

每当遇到异常,每当试图在列表视图项的按钮单击上显示AlertDialog时,我都在使用以下代码:

public class MyAdapter extends ArrayAdapter<Transport> {
    Context context;
    .......

public MyAdapter(Context context, int resource, ArrayList<Transport> arrayList) {
        super(context, resource, arrayList);
        layoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.context = context;
        ..........
      }

@Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // convert view = design
        view = convertView;
        if (view == null) {
            viewHolder = new ViewHolder();
            view = layoutInflater.inflate(resource, null);

viewHolder.btnDelete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v) {                 

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

                    alertDialogBuilder.setTitle("Title");
                    alertDialogBuilder
                        .setMessage("Message")
                        .setCancelable(false)
                        .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                dialog.cancel();

                            }
                          })
                        .setNegativeButton("No",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {

                                dialog.cancel();

                            }
                        });

                        AlertDialog alertDialog = alertDialogBuilder.create();
                        alertDialog.show();                                 

            }
        });

我不知道我在哪里mistake 因为我在许多SO链接上看到过,所以即使在我遇到异常之后,我们也必须使用context代替getApplicationContext()

日志:

FATAL EXCEPTION: main
Process: app.android.fields, PID: 920
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:540)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.and.field.MyAdapter$1.onClick(MyAdapter.java:100)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)

这里是line在那里我得到exception

 alertDialog.show();

对话框需要活动上下文。 因此,首先要确保传递给适配器的上下文对象是Activity ,然后使用

new AlertDialog.Builder((Activity) context);

或者您可以使用

new AlertDialog.Builder(v.getContext());

如ρяσsρєяK所建议。

顺便说一下,由于扩展ArrayAdapter具有上下文,因此您可以在不将其传递给构造函数的情况下获取上下文。 ->您可以使用getContext()达到目标。 但是问题更加严重,因为在某些特殊情况下,上下文不是null,但是不能用于任何事情。(我有同样的问题,仅在rxJava环境中)。因此,请尝试提取整个AlertDialog。构建器零件属于不同的类,并在其他地方进行了上下文初始化。 一个简短的例子:

public class DialogManager {

    private static DialogManager instance = null;

    private Context context;

    public void initialize(Context context) {
        this.context = context;
    }

    public static DialogManager getInstance() {
        if (instance == null) {
            instance=new DialogManager();
        }
        return instance;
    }

    public void showBasicErrorDialog(String title, String message) {
        AlertDialog dialog = new AlertDialog.Builder(getContext())
                .setTitle(title)
                .setMessage(message)
                .setTitle(getContext().getString(R.string.error))
                .setPositiveButton(getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //TODO anything you want
                        dialog.dismiss();
                    }   
                // TODO .setNegativeButton .. etc.

                }).create();

        dialog.show();

    }

    public Context getContext() {
        return context;
    }
}

并将此行添加到您的主活动或应用程序中:

DialogManager.getInstance().initialize(this);

然后,可以在getView()函数中调用:

    // ...
    viewHolder.btnDelete.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(final View v) {
        DialogManager.getInstance().showBasicErrorDialog("Title","Message");
    }
});

这样更通用,您也可以使用其他类中的对话框。 我不确定是否可以解决问题,但是应该。

暂无
暂无

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

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