Android Studio开发AlertDialog时变量未定义问题求助
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

