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
相关产品推荐
相关产品推荐

