CS50 Android 图鉴:为什么我的 'Catch Pokemon' 按钮只能工作一次?
CS50 Android Pokedex: Why does my 'Catch Pokemon' button work only once?
这里是activity_pokemon.xml
中的相关代码:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/catching_button"
android:text="STATE 1"
android:onClick="toggleCatch"/>
这里是PokemonActivity.java
中的相关代码:
public class PokemonActivity extends AppCompatActivity {
...
private Button buttonView;
@Override
protected void OnCreate(...) {
...
buttonView = findViewById(R.id.catching_button);
...
}
...
// Implements catching functionality.
public boolean pokemonIsCaught = false;
public void toggleCatch(View view) {
// Catch the Pokemon if it is not caught.
if (!pokemonIsCaught) {
pokemonIsCaught = true;
buttonView.setText("Release");
}
// Release the Pokemon if it is caught.
if (pokemonIsCaught) {
pokemonIsCaught = false;
buttonView.setText("Catch");
}
}
预期行为
- 按钮的初始文本是
STATE 1
(Catch
的占位符)。 (这有效。)
- 按下按钮会将其文本更改为
Release
。 (相反,文本更改为 Catch
。这让我感到困惑 -- pokemonIsCaught
最初是 False
!)
- 任何后续按下按钮都会在
Release
和 Catch
之间切换其文本。 (相反,文本停留在 Catch
。)
当您第一次单击时,单击更改 pokemonIsCaught
为 true,然后再次更改回来(因为第二个 if 语句现在为 true)。所以基本上你的方法改变 pokemonIsCaught
这样
false ->(点击)true(第一个如果)false(第二个如果)
这应该会如您所愿
public void toggleCatch(View view) {
// Catch the Pokemon if it is not caught.
if (!pokemonIsCaught) {
pokemonIsCaught = true;
buttonView.setText("Release");
} else { // Release the Pokemon if it is caught.
pokemonIsCaught = false;
buttonView.setText("Catch");
}
}
这里是activity_pokemon.xml
中的相关代码:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/catching_button"
android:text="STATE 1"
android:onClick="toggleCatch"/>
这里是PokemonActivity.java
中的相关代码:
public class PokemonActivity extends AppCompatActivity {
...
private Button buttonView;
@Override
protected void OnCreate(...) {
...
buttonView = findViewById(R.id.catching_button);
...
}
...
// Implements catching functionality.
public boolean pokemonIsCaught = false;
public void toggleCatch(View view) {
// Catch the Pokemon if it is not caught.
if (!pokemonIsCaught) {
pokemonIsCaught = true;
buttonView.setText("Release");
}
// Release the Pokemon if it is caught.
if (pokemonIsCaught) {
pokemonIsCaught = false;
buttonView.setText("Catch");
}
}
预期行为
- 按钮的初始文本是
STATE 1
(Catch
的占位符)。 (这有效。) - 按下按钮会将其文本更改为
Release
。 (相反,文本更改为Catch
。这让我感到困惑 --pokemonIsCaught
最初是False
!) - 任何后续按下按钮都会在
Release
和Catch
之间切换其文本。 (相反,文本停留在Catch
。)
当您第一次单击时,单击更改 pokemonIsCaught
为 true,然后再次更改回来(因为第二个 if 语句现在为 true)。所以基本上你的方法改变 pokemonIsCaught
这样
false ->(点击)true(第一个如果)false(第二个如果)
这应该会如您所愿
public void toggleCatch(View view) {
// Catch the Pokemon if it is not caught.
if (!pokemonIsCaught) {
pokemonIsCaught = true;
buttonView.setText("Release");
} else { // Release the Pokemon if it is caught.
pokemonIsCaught = false;
buttonView.setText("Catch");
}
}