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

Android Studio报错:MainActivity不是封闭类,三级可展开列表求助

解决‘MainActivity is not an enclosing class’错误

嘿,这个问题很好解决!咱们先搞清楚错误的根源:

你的Activity类名叫ThreeLevelExpandableListView,但在ParentLevel内部类的getChildView方法里,你错误地用了MainActivity.this来传递上下文——可你的代码里根本没有叫MainActivity的类,它不是包围当前内部类的Activity,所以编译器就报错啦。

修复步骤

只需要把那行错误的代码替换成下面两种方式之一就行:

方式1:使用当前Activity的引用

直接用你的Activity类名来获取上下文:

SecondLevelExpandableListView secondLevelELV = new SecondLevelExpandableListView(ThreeLevelExpandableListView.this);

方式2:使用已经持有的context变量

因为ParentLevel类的构造方法已经接收并保存了context对象,直接用它更简洁:

SecondLevelExpandableListView secondLevelELV = new SecondLevelExpandableListView(context);

额外小提示

顺便检查一下你的activity_main.xml布局文件,确保里面的ExpandableListView的id确实是mainList,和代码里findViewById(R.id.mainList)的引用对应上,避免后续出现找不到控件的问题哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:14:37