Android Studio点击Button根据Spinner选中值设置TextView内容不生效求助
问题原因
1. 逻辑运算符优先级错误
Java中&&优先级高于||,你原有条件的逻辑完全不符合预期。你原本想表达的是「墙类型是Trockenbau 且 墙厚是100mm或125mm 且 其余选项全部匹配」,但原有写法下只要满足spinnerWandart是Trockenbau且墙厚100mm这一个条件,不管其他Spinner选什么,整个if都会判定为true,逻辑完全混乱。
2. 条件分支结构错误
你用了两个独立的if语句,第二个if还附带else分支。就算第一个if匹配成功给TextView赋值,只要第二个if不匹配,else就会把之前设置的值清空,导致第一个if的结果被覆盖。
3. 按钮点击事件冲突
你在xml的Button标签中声明了android:onClick="onButtonClick",同时又在Java代码里给按钮设置了setOnClickListener,二者会冲突,只会有一个生效。
4. 潜在空指针风险
如果Spinner没有选中任何项,getSelectedItem()会返回null,直接调用toString()会触发空指针崩溃。
5. 字符串比较规则错误
所有字符串值对比都需要用equals(),不能用==,你之前只修改了第一个对比,其余所有字符串对比都需要替换。
修复步骤
第一步:删除xml中的点击事件声明
删掉Button标签里的android:onClick="onButtonClick"属性,统一用Java代码设置监听。
第二步:初始化所有控件
在Activity的onCreate方法中,setContentView之后先绑定所有控件:
// 初始化所有Spinner和TextView AppCompatSpinner spinnerWandart = findViewById(R.id.spinner_wandart); AppCompatSpinner spinnerFertigwandstaerke = findViewById(R.id.spinner_fertigwandstaerke); AppCompatSpinner spinnerAusgangsmass = findViewById(R.id.spinner_ausgangsmass); AppCompatSpinner spinnerBreite = findViewById(R.id.spinner_breite); AppCompatSpinner spinnerHoehe = findViewById(R.id.spinner_hoehe); TextView tvArtNr = findViewById(R.id.tv_artnr); Button btnBestaetigen = findViewById(R.id.btn_bestaetigen);
第三步:修改点击事件逻辑
btnBestaetigen.setOnClickListener(v -> { // 统一获取选中值并做非空处理 String wandart = spinnerWandart.getSelectedItem() != null ? spinnerWandart.getSelectedItem().toString() : ""; String wandstaerke = spinnerFertigwandstaerke.getSelectedItem() != null ? spinnerFertigwandstaerke.getSelectedItem().toString() : ""; String ausgangsmass = spinnerAusgangsmass.getSelectedItem() != null ? spinnerAusgangsmass.getSelectedItem().toString() : ""; String breite = spinnerBreite.getSelectedItem() != null ? spinnerBreite.getSelectedItem().toString() : ""; String hoehe = spinnerHoehe.getSelectedItem() != null ? spinnerHoehe.getSelectedItem().toString() : ""; // 抽离公共匹配条件,用括号控制||的优先级 boolean commonMatch = wandart.equals("Trockenbau") && (wandstaerke.equals("100 mm") || wandstaerke.equals("125 mm")) && ausgangsmass.equals("Türblattmaß") && breite.equals("610 mm"); // 用if-else if结构避免分支覆盖 if (commonMatch && hoehe.equals("2110 mm")) { tvArtNr.setText("EKID610SB"); } else if (commonMatch && hoehe.equals("1985 mm")) { tvArtNr.setText("EKID610SA"); } else { tvArtNr.setText(""); } });
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

