Android Studio 3.0.1中finish()方法无法解析问题求助
Let's break down why you're seeing this error and how to fix it quickly:
The Root Cause
The finish() method is a member of the Activity class, not the base Context class. In your original code (inside QAnswerQuestion.java), you're calling finish() directly on the Activity instance (this refers to QAnswerQuestion, which is an Activity), so it works perfectly.
When you moved the code to the static lastQuestionDialog method in UIResponse.java, you're passing a Context parameter. Since Context doesn't have a finish() method, the IDE throws the "can't resolve method" error.
Solution 1: Use Activity as the Parameter Type (Simplest & Safest)
Change the method's parameter from Context to Activity—since QAnswerQuestion is an Activity, this is fully compatible, and you can directly call finish() on the Activity instance:
static void lastQuestionDialog(final Activity activity, List<Question> list) { List<Integer> wrongList = UIResponse.checkAnswer(list); if (wrongList.size() == 0) { new AlertDialog.Builder(activity).setTitle("Info") .setMessage("You are awesome and all answers are correct!") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { activity.finish(); // Now this works perfectly } }).setNegativeButton("Cancel", null).show(); } }
Call it exactly like before:
UIResponse.lastQuestionDialog(QAnswerQuestion.this, list);
Solution 2: Keep Context Parameter with Type Check (More Flexible)
If you need to support non-Activity Contexts in this method later, add a type check to safely cast the Context to an Activity before calling finish():
static void lastQuestionDialog(final Context context, List<Question> list) { List<Integer> wrongList = UIResponse.checkAnswer(list); if (wrongList.size() == 0) { new AlertDialog.Builder(context).setTitle("Info") .setMessage("You are awesome and all answers are correct!") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Ensure the Context is an Activity before calling finish() if (context instanceof Activity) { ((Activity) context).finish(); } } }).setNegativeButton("Cancel", null).show(); } }
This avoids crashes if someone accidentally passes a non-Activity Context (like an Application Context) to the method.
内容的提问来源于stack exchange,提问作者Jack Wilson

