Android Studio中R标红无法解析但构建成功,应用无法启动求助
Hey there, let's work through this annoying issue you're dealing with—your project builds successfully, but Android Studio keeps flagging R as an unresolved symbol, and your app won't launch. Let's break down the most common fixes that usually resolve this:
Common Troubleshooting Steps
First, check for broken resource files
This is the #1 reason for this problem. Even if the build says it succeeded, a tiny typo or invalid entry in an XML resource (likeactivity_main.xml, drawables, strings, or styles) can break the IDE's ability to generate theRclass properly. Go through all your resource files:- Look for unclosed XML tags
- Check for invalid characters in string values (like unescaped apostrophes: use
\'instead of') - Ensure all drawable filenames use lowercase letters and underscores (no spaces or uppercase)
Invalidate IDE caches and restart
Corrupted cache data is a frequent culprit. Head toFile > Invalidate Caches... > Invalidate and Restart—this clears out stale cached files and forces Android Studio to re-sync and regenerateRfrom scratch.Double-check your imports
Make sure you don't have an accidental import ofandroid.Rin yourMainActivity.java. Your code doesn't show this, but it's an easy mistake to make—if it's there, delete it immediately (your app'sRclass is auto-recognized since it's in the same package).Manually sync Gradle
Click the elephant icon (Sync Project with Gradle Files) in the toolbar. Sometimes the IDE fails to sync automatically after a rebuild, leaving old, brokenRreferences in place.Verify package name consistency
Confirm the package name in yourAndroidManifest.xml(com.example.zeeshan.myapplication) matches the package declaration at the top ofMainActivity.java. Your code looks correct here, but it's worth a quick double-check.Clean and rebuild properly
Go through the full sequence:Build > Clean Project, wait for it to finish, thenBuild > Rebuild Project. A quick clean/rebuild might not fully regenerateR, so give this full process a shot.
If All Else Fails
If none of the above works, try deleting the .idea and .gradle folders in your project root directory, then re-open Android Studio. This resets the IDE's project configuration entirely, which can fix stubborn cache or sync issues.
Looking at your provided code, your MainActivity and AndroidManifest.xml are structurally correct—so the issue is almost certainly related to resource errors or IDE sync/cache problems.
内容的提问来源于stack exchange,提问作者Muhammad Zeeshan

