Android Java无XML动态开发按钮与TextView 点击应用崩溃排查
空指针故障原因
根本问题是变量作用域遮蔽:你在类中声明的成员变量没有被正确赋值,始终为null,触发了空指针异常。
具体错误点
- 你在
MainActivity类顶部声明了3个成员变量:layout、set、goldButton,但在onCreate方法中初始化时,错误地给这些变量加了类型前缀,把它们变成了只在onCreate内部生效的局部变量:- 错误代码:
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.CL_1);这里的ConstraintLayout前缀让这行的layout是局部变量,类的成员layout从来没被赋值,一直是null。 - 错误代码:
ConstraintSet set = new ConstraintSet();同理,这里的set是局部变量,类的成员set始终为null。 - 错误代码:
Button goldButton = new Button(this);同理,这里的goldButton是局部变量,类的成员goldButton始终为null。
- 错误代码:
- 你在点击监听器
ShadeChangeListener中调用的是类成员的layout和set,这两个变量都是null,所以执行到layout.addView(textView);时就会直接崩溃。
修复方案
把onCreate里初始化这三个变量的代码删掉类型前缀,让赋值直接作用在类成员上:
- 把
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.CL_1);改为:layout = (ConstraintLayout) findViewById(R.id.CL_1); - 把
ConstraintSet set = new ConstraintSet();改为:set = new ConstraintSet(); - 把
Button goldButton = new Button(this);改为:goldButton = new Button(this);
额外提示:你的作业要求是不使用XML布局、全代码开发,目前你还在依赖XML的
R.layout.activity_main和R.id.CL_1,后续可以直接在代码里创建根ConstraintLayout,完全去掉对XML布局的依赖。
内容的提问来源于stack exchange,提问作者ccase3
相关产品推荐
相关产品推荐

