Android Studio MyFirstApp教程报错:Cannot resolve symbol "setText"
Hey there! I’ve been in your shoes before working through the MyFirstApp tutorial—let’s get this error sorted out quickly. That Cannot resolve symbol "setText" message usually means Android Studio can’t recognize that you’re calling the method on a valid TextView instance. Here are the most common fixes:
1. Make sure you’ve initialized your TextView correctly
You probably forgot to connect your Java code to the TextView in your layout. First, double-check that you’ve:
- Added a TextView with a unique ID in your
activity_display_message.xmllayout file:<TextView android:id="@+id/display_message_text" android:layout_width="wrap_content" android:layout_height="wrap_content"/> - Used
findViewByIdto get a reference to that TextView in youronCreatemethod before callingsetText:
Note: Replace@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_message); // Don't skip this line! // Get the message from the intent Intent intent = getIntent(); String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); // Initialize the TextView and set its text TextView textView = findViewById(R.id.display_message_text); textView.setText(message); }display_message_textwith the actual ID you used in your layout.
2. Clear Android Studio’s cache
Sometimes the IDE gets confused by stale cache files. Try this:
- Go to
File > Invalidate Caches... - Select
Invalidate and Restart - Let Android Studio rebuild your project once it restarts—this often fixes weird symbol resolution issues.
3. Verify your layout and import setup
- You already have the correct import (
import android.widget.TextView;), so that’s good. - Ensure you’re calling
setContentView(R.layout.activity_display_message);before trying to access any views—without this, your activity doesn’t know which layout to use, sofindViewByIdwill returnnull, and calling methods on null will trigger this error.
4. If you’re using View Binding (newer tutorial versions)
If the tutorial recommends View Binding instead of findViewById, make sure you’ve enabled it in your app-level build.gradle file:
android { ... buildFeatures { viewBinding true } }
Then use it like this in your activity:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityDisplayMessageBinding binding = ActivityDisplayMessageBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); Intent intent = getIntent(); String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); binding.displayMessageText.setText(message); }
Give these steps a try—most likely, the issue is just missing the findViewById call or forgetting to set the content view.
内容的提问来源于stack exchange,提问作者user71311

