You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android绘图应用运行报错:setContentView无代码提示却出现异常

Troubleshooting the 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 CanvasView uses 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_width instead of android:layout_witdh)
  • Clean and rebuild your project
    Android Studio’s cache can sometimes get out of sync, leading to broken references to the auto-generated R class. Do this step-by-step:

    1. Go to Build > Clean Project
    2. Then Build > Rebuild Project
    3. If that doesn’t work, try File > Invalidate Caches... > Invalidate and Restart to clear all cached data
  • Ensure you’re importing the correct R class
    Open your MainActivity.java and check the imports. You should see something like import com.yourprojectpackage.R; — not import 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 takes Context and AttributeSet. If your CanvasView is missing this constructor, it’ll throw an inflation error that points back to setContentView. 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 like InflateException or ClassNotFoundException — these will give you the real root cause (e.g., missing constructor, invalid View class name).

内容的提问来源于stack exchange,提问作者Louis Evans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:10:10