Android Studio中通过Intent传递文本后TextView显示异常问题求助
Hey there! Let's figure out why your TextView isn't showing the expected text from the Intent—even though you've done this a bunch before, it's easy to overlook a tiny detail here. Let's walk through the most common fixes step by step:
Typos are the #1 culprit here! Make sure the string key you use when putting the extra matches exactly what you use to retrieve it. Even a single uppercase/lowercase difference will break things. Here's an example of the correct pairing:
- Sending from the first Activity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class); intent.putExtra("USER_MESSAGE", "Hey, this is the text to pass!"); startActivity(intent);
- Receiving in the second Activity:
String message = getIntent().getStringExtra("USER_MESSAGE"); // Same key, no typos!
Sometimes the issue isn't the Intent—it's how you're updating the TextView itself. Make sure you:
- Call
setContentView()before trying to find the TextView withfindViewById()(you can't reference views before the layout is inflated) - Actually use
setText()with the received string, and handle null cases to avoid crashes. Example:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); // This comes first! TextView displayTextView = findViewById(R.id.your_text_view_id); String receivedText = getIntent().getStringExtra("USER_MESSAGE"); if (receivedText != null) { displayTextView.setText(receivedText); } else { displayTextView.setText("Oops, no message received!"); } }
If you're using a base Activity, custom IntentFilters, or starting the second Activity from a fragment, double-check that the extra isn't getting removed or modified along the way. When starting from a fragment, make sure you use requireActivity() as the context for your Intent, not a null or incorrect context.
Add a log statement to confirm what your second Activity is getting from the Intent. This will tell you if the problem is with the data transmission or the TextView:
String receivedText = getIntent().getStringExtra("USER_MESSAGE"); Log.d("SecondActivityLog", "Received text: " + receivedText);
If the log shows the correct text but the TextView is still wonky, the issue is likely layout-related. Check if the TextView is visible (not gone or invisible), has a text color that contrasts with its background, or if another view is covering it up.
Since you're passing text, getStringExtra() is the right call—but don't accidentally use getExtras().get(...) without casting it properly, which can lead to weird display issues or crashes. Stick to the type-specific methods for extras when you can.
If none of these fix it, that screenshot of the abnormal display would help narrow things down—chances are it's a layout styling issue (like text size being 0, or the TextView having no width/height set).
内容的提问来源于stack exchange,提问作者LoveToSpooch

