Java Android-方法setText()正在更改小部件的文本,即使它从未被调用
我这里有一个基本的代码块,在活动之间传递简单的数据。基本上,当收到数据时,更改按钮的文本:Java Android-方法setText()正在更改小部件的文本,即使它从未被调用,java,android,side-effects,Java,Android,Side Effects,我这里有一个基本的代码块,在活动之间传递简单的数据。基本上,当收到数据时,更改按钮的文本: Bundle intentData = getIntent().getExtras(); if (intentData != null) { String passedMsg = intentData.getString("userMsg"); Button mainButton = (Button) findViewById(R.id.main_button); mai
Bundle intentData = getIntent().getExtras();
if (intentData != null) {
String passedMsg = intentData.getString("userMsg");
Button mainButton = (Button) findViewById(R.id.main_button);
mainButton.setText(passedMsg);
}
但是,即使在if条件失败的情况下,按钮的文本仍然会更改。当我注释掉行mainButton.setText(passedMsg)时代码>,按钮的文本保持不变
似乎无论是否到达该行代码,setText()
的出现都会改变按钮的文本。它为什么会这样做?或者您正在检查的条件不是您应该检查的条件,或者在您编译的代码中,if语句后面紧跟着一个分号,放在大括号之前 显然,您的代码块被执行了多次。要证明这一点,请执行以下操作
static boolean initialized = false;
public void enteredBlockOfCode() {
if(!initialized) {
// code here only runs once ...
initialized = true;
}
}
似乎intentData
从未传递过null
,因此if语句不会失败它绝对不会失败。或者其他地方正在设置文本,或者您对if的方向不正确。您确定“if”语句失败吗?您是否在“if”主体中添加了一些Log.d
调用?因此,执行一些日志调用可以确认if语句没有失败。似乎null
没有传递给intentdata您应该检查intent是否有额外的密钥,而不是额外的是否为null。