Android Studio 3.1.1中XML报错not well-formed (invalid token)求助
Hey there! Let's work through this XML syntax error you're hitting—it's one of the most common hurdles when starting out with Android layout files, so you're definitely not alone here.
What's causing this error?
The not well-formed (invalid token) message from AAPT tells us there's a syntax mistake in your activity_main.xml file, specifically on line 20. XML is super strict about its structure, so even tiny typos can trigger this.
Step-by-step troubleshooting for line 20
Jump straight to line 20 in your layout file and check for these common issues:
- Unclosed or malformed tags:
- Did you forget to close a tag? Like
<Button ...>without a matching</Button>? - Did you miss the
/in a self-closing tag? For example,<ImageView android:src="@drawable/icon"should be<ImageView android:src="@drawable/icon"/>.
- Did you forget to close a tag? Like
- Mismatched or missing quotes:
- All attribute values need to be wrapped in quotes (either single or double, but don't mix them incorrectly). For example,
android:text=Hellois invalid—useandroid:text="Hello"instead. - If you need to include quotes inside a value, escape them properly:
android:text='Hello "World"'orandroid:text="Hello \'World\'".
- All attribute values need to be wrapped in quotes (either single or double, but don't mix them incorrectly). For example,
- Unescaped special characters:
- XML doesn't allow raw
&,<, or>characters in text. Replace them with their escape sequences:&,<,>. Alternatively, wrap the problematic text in a CDATA section:<![CDATA[This & that < are okay here]]>.
- XML doesn't allow raw
- Invalid characters in names:
- Tag names and attribute names can't have spaces, special characters (like
!,@), or start with a number. For example,android:layout width(with a space) is invalid—it should beandroid:layout_width.
- Tag names and attribute names can't have spaces, special characters (like
Example of a fix
Suppose line 20 looks like this (with a missing quote):
<TextView android:id="@+id/myText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=My Favorite Websites/>
Correct it by adding quotes around the text value:
<TextView android:id="@+id/myText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="My Favorite Websites"/>
Pro tip from Android Studio
Keep an eye on the editor—Android Studio will highlight syntax errors in red. Hover over the red line with your mouse, and it'll show you a more specific hint about what's wrong. If you're still stuck, feel free to share the code around line 20, and we can pinpoint the issue faster!
内容的提问来源于stack exchange,提问作者Steve




