You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio开发AlertDialog时变量未定义问题求助

解决AlertDialog中Context/变量未定义错误的方案

Hey there! Let's fix that error you're seeing with your AlertDialog. The issue actually boils down to how the this keyword behaves inside anonymous inner classes like the button click listeners for your dialog.

What's Causing the Error?

When you use this inside the setPositiveButton's OnClickListener, it doesn't refer to your MainActivity instance—it refers to the DialogInterface.OnClickListener anonymous class instead. Methods like FileHelper.escreve() and Toast.makeText() require a valid Android Context (your Activity), so passing the wrong this leads to the "variable undefined" error you're encountering.

Corrected Code

Here's the fixed version of your onItemClick method, with the key changes highlighted:

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int posicao, long id) {
    AlertDialog confirmDialog = new AlertDialog.Builder(this)
            .setTitle("Confirmação")
            .setMessage("De certeza que pretende eliminar a tarefa?")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    tarefas.remove(posicao);
                    adapt.notifyDataSetChanged();
                    // Use MainActivity.this to reference your Activity's Context
                    FileHelper.escreve(tarefas, MainActivity.this);
                    // Same fix for the Toast
                    Toast.makeText(MainActivity.this, "Tarefa Eliminada", Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // Empty implementation is okay here—you can add logic later if needed
                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
}

Why This Works

Using MainActivity.this explicitly tells the compiler to use your MainActivity instance as the Context, which is exactly what FileHelper.escreve() and Toast.makeText() need to run correctly. This should resolve the error and let your delete confirmation dialog work as expected.

A quick side note: Double-check that your FileHelper.escreve method accepts a Context parameter—since we're passing MainActivity.this now, this should match what the method expects.

内容的提问来源于stack exchange,提问作者Dinis Martins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 08:38:12