Android绘图应用运行报错:setContentView无代码提示却出现异常
setContentView(R.layout.activity_main); Error in Your Android Drawing App Hey there! Let’s break down why that line is causing issues even though your code doesn’t show any underlined errors. Here are the most common fixes to try:
Double-check your activity_main.xml for hidden issues
Even if the editor doesn’t flag it, layout files can have subtle problems that break inflation. For example:- Make sure your custom
CanvasViewuses the full package name in the XML (like<com.yourappname.CanvasView ...>instead of just<CanvasView>) - Verify all XML tags are properly closed, and there are no typos in attribute names (e.g.,
android:layout_widthinstead ofandroid:layout_witdh)
- Make sure your custom
Clean and rebuild your project
Android Studio’s cache can sometimes get out of sync, leading to broken references to the auto-generatedRclass. Do this step-by-step:- Go to
Build > Clean Project - Then
Build > Rebuild Project - If that doesn’t work, try
File > Invalidate Caches... > Invalidate and Restartto clear all cached data
- Go to
Ensure you’re importing the correct
Rclass
Open your MainActivity.java and check the imports. You should see something likeimport com.yourprojectpackage.R;— notimport android.R;(the latter refers to system resources, not your app’s custom layouts/views).Check your custom CanvasView’s constructors
When a View is inflated from XML, Android calls its constructor that takesContextandAttributeSet. If your CanvasView is missing this constructor, it’ll throw an inflation error that points back tosetContentView. Make sure you have all three standard constructors:public class CanvasView extends View { public CanvasView(Context context) { super(context); init(); } public CanvasView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CanvasView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { // Your initialization code (Paint setup, etc.) } }Dig into the full error log
The Run window’s mention of line 14 is just the starting point. Look further down in the log for exceptions likeInflateExceptionorClassNotFoundException— these will give you the real root cause (e.g., missing constructor, invalid View class name).
内容的提问来源于stack exchange,提问作者Louis Evans

