我想点击ImageView,当达到一定数量的点击时,我希望Imageview更改图像。 这是我的代码,但我不知道问题出在哪里。 没有错误或其他什么。 图片不会改变 请你帮帮我吧 感谢
public class MainActivity extends AppCompatActivity {
private ImageView megg;
int counter = 0;
int readhighscore;
private TextView mnumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mnumber = (TextView) findViewById(R.id.number);
mnumber.setText(Integer.toString(readhighscore));
megg = (ImageView) findViewById(R.id.egg);
megg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter++;
readhighscore = counter;
mnumber.setText(Integer.toString(readhighscore));
}
});
if (counter == 10){
ImageView megg = (ImageView) findViewById(R.id.egg);
megg.setImageResource(R.drawable.egg100);
}
if (counter == 100){
ImageView megg = (ImageView) findViewById(R.id.egg);
megg.setImageResource(R.drawable.egg100);
}
if (counter == 500){
ImageView megg = (ImageView) findViewById(R.id.egg);
megg.setImageResource(R.drawable.egg500);
}
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
counter = prefs.getInt("highscore", readhighscore);
}
@Override
protected void onPause() {
super.onPause();
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("highscore", readhighscore);
editor.commit();
}
@Override
protected void onResume() {
super.onResume();SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
counter = prefs.getInt("highscore", readhighscore);
readhighscore = counter;
mnumber.setText(Integer.toString(readhighscore));
}
}
答案 0 :(得分:0)
将flow语句放在onClick方法中。目前,If statements
位于OnClickListener
之外,因此每次点击都不会调用它,并且您希望每次点击都执行此检查。
@Override
public void onClick(View v) {
counter++;
if (counter == 10){
ImageView megg = (ImageView) findViewById(R.id.egg);
megg.setImageResource(R.drawable.egg100);
}
if (counter == 100){
ImageView megg = (ImageView) findViewById(R.id.egg);
megg.setImageResource(R.drawable.egg100);
}
if (counter == 500){
ImageView megg = (ImageView) findViewById(R.id.egg);
megg.setImageResource(R.drawable.egg500);
}
}
});