无法显示简单的警报对话框

时间:2017-05-19 13:23:54

标签: android android-alertdialog

我在线性布局上设置了一个on click侦听器。这是代码:

Context context = this;
  LinearLayout credit = (LinearLayout) findViewById(R.id.credits_activity);
    credit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder creditDialog = new AlertDialog.Builder(context);
            creditDialog.setTitle(R.string.credits_title)
                    .setMessage(R.string.credits_content)
                    .setNeutralButton("cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
            AlertDialog dialog = creditDialog.create();
            dialog.show();
        }
    });

任何人都可以说出错了吗?

2 个答案:

答案 0 :(得分:1)

您在AlertDialog.builder中使用getapplicationcontext()(getapplicationcontext())

 LinearLayout credit = (LinearLayout) findViewById(R.id.credits_activity);
        credit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder creditDialog = new AlertDialog.Builder(YourActivityName.this);
                creditDialog.setTitle(R.string.credits_title)
                        .setMessage(R.string.credits_content)
                        .setNeutralButton("cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).show();
            }
        });

答案 1 :(得分:0)

代替getApplicationContext()传递ActivityName.this