Android开发新建带FAB的MainActivity2缺失content_main2.xml求助
Hey there! As an Android dev who’s stumbled through these template quirks before, let’s get your MainActivity2 set up smoothly. Here’s what’s going on and how to fix it:
Why content_main2.xml is missing
Android Studio’s Activity templates vary based on the type you pick. Some FAB-included templates skip the content_*.xml split and dump all layout code directly into activity_main2.xml—this is intentional for simpler setups, but if you want the same split structure as your first project, we can add it manually.
Step 1: Manually create content_main2.xml
This is the fastest way to match your original project’s layout structure:
- Right-click your
res/layoutfolder → New → Layout Resource File - Name it
content_main2, set the root layout toConstraintLayout(or whatever you used incontent_main.xml), and check the "Launcher Layout" box if needed - Paste this base code into
content_main2.xml(adjust to match your app’s theme):
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main2"> <!-- Add your UI elements (TextViews, RecyclerViews, etc.) here --> </androidx.constraintlayout.widget.ConstraintLayout>
- Open
activity_main2.xml, remove any default content layout code (like a pre-added TextView), and add this include tag between theAppBarLayoutandFloatingActionButtonto link your new content file:
<include layout="@layout/content_main2" />
Step 2: Fix other MainActivity2 creation issues
If you’re having trouble creating the Activity itself, try these checks:
- Manual class registration: If you made the Java/Kotlin file manually, don’t forget to add it to
AndroidManifest.xml:<activity android:name=".MainActivity2" android:exported="false" /> - Clear template cache: Sometimes Android Studio’s cached templates glitch. Fix this by going to File → Invalidate Caches... → Invalidate and Restart, then try creating the Activity again.
- Pick the right template: When creating a new Activity, select Empty Views Activity (not "Empty Activity")—this template generates the split
activity_*andcontent_*layout files by default, including the FAB.
Give these steps a try, and you’ll have MainActivity2 working just like your original project in no time!
内容的提问来源于stack exchange,提问作者Gene Xu

