2 回答
TA贡献1786条经验 获得超13个赞
复制代码是一种不好的做法。现在你有重复的方法findViewById。为避免这种情况,您应该在类中创建一个全局变量Activity1。这也将是您的问题的解决方案:
public class Activity1 extends AppCompatActivity {
private final Double TIP = 10.0;
private TextView tipView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
setDefaultValues();
}
private void setDefaultValues() {
tipView = findViewById(R.id.tipView);
tipView.setText(getString(R.string.main_msg_tip, Double.toString(TIP)));
}
public void onClickToggleButton(View view) {
switch (view.getId()) {
case (R.id.toggleButtonBad):
tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
break;
}
}
}
TA贡献1895条经验 获得超3个赞
您正在尝试从单击视图(例如按钮)中查找视图,而“tipView”位于主视图容器中。所以更新你的方法“onClickToggleButton”如下:
public void onClickToggleButton(View view) {
TextView tipView = findViewById(R.id.tipView);
switch (view.getId()) {
case (R.id.toggleButtonBad):
tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
break;
}
}
添加回答
举报
