Android报错:DrawerLayout需用MeasureSpec.EXACTLY测量,求排查解决
java.lang.IllegalArgumentException: DrawerLayout must be measured with MeasureSpec.EXACTLY Alright, let's break down this error you're hitting with DrawerLayout—it's a straightforward fix once you spot the root cause.
What's Causing This?
The error message spells it out clearly: DrawerLayout requires an exact measurement spec (MeasureSpec.EXACTLY) to render properly. Looking at your main layout file, here's where the problem lives:
<android.support.v4.widget.DrawerLayout android:id="@+id/navigation_Drawerlayout" android:layout_width="wrap_content" <!-- 🚨 This is the culprit --> android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start">
When you set layout_width="wrap_content", Android uses the MeasureSpec.AT_MOST measurement mode for the view—meaning it only takes as much space as its content needs. But DrawerLayout relies on a fixed, exact size (either matching its parent or a hardcoded dimension) to correctly calculate the position and size of its main content and sliding drawer.
The Fix
Simply change the layout_width of your DrawerLayout from wrap_content to match_parent:
<android.support.v4.widget.DrawerLayout android:id="@+id/navigation_Drawerlayout" android:layout_width="match_parent" <!-- ✅ Fixed to match parent --> android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start">
Quick Extra Note
DrawerLayout is built to act as a full-screen (or full-parent) container for your main content and navigation drawer. Using match_parent ensures it occupies all available width, which is the standard use case. If you have a specific need for a fixed-width drawer container, you could also use a hardcoded dimension like 300dp—just avoid wrap_content entirely, and you won't run into this error again.
内容的提问来源于stack exchange,提问作者Sumit Kumawat

