为什么if语句在“图像”按钮中不起作用?

时间:2019-04-27 23:54:22

标签: java android

您好,我是本网站的新手,所以,如果我有任何错误,请原谅。对于学校,我需要编写一个应用程序,我想编写一个类似于旧Egg应用程序的应用程序,在该应用程序中,您需要单击1.000.000次。

我的柜台可以工作,但我想让鸡蛋破碎。为此,我想使用 if语句,这样我可以使其在200次后中断,依此类推。

我的问题是,如果我按下按钮,则图像会在第一次切换。并非我第三次期望的那样

有人知道我的问题是什么吗?

PS:我是Java新手,所以代码可能并不性感

package com.example.die_vierte;

import android.content.Intent;
import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.webkit.SafeBrowsingResponse;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    private Object TextView;

    int eggcounter;
    ImageButton ImgButton;

    android.widget.TextView textClicks;
    private Object SafeBrowsingResponse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        eggcounter = 10000000;
        final ImageButton ImgButton = findViewById(R.id.eggBtn);

        ImgButton.setOnClickListener(
                new View.OnClickListener() {

                    public void onClick(View view) {
                        eggcounter = eggcounter - 1;
                        updateEgg();

                        if (eggcounter > 999998) {

                            ImgButton.setImageResource(R.drawable.egg_2);
                        }

                    }
                }
        );

    public void updateEgg() {
        textClicks = (TextView) findViewById(R.id.textScore);
        textClicks.setText(eggcounter + " ");

    }

2 个答案:

答案 0 :(得分:0)

首次单击该按钮时,“ eggcounter”位于999999。
该值大于999998,因此if语句为true,因此图像已更改。

我猜您应该将'>'更改为'<',以便在第三次单击之前图像不会更改。

答案 1 :(得分:0)

首先,您。setText()方法不正确,应该这样使用:

textClicks.setText(String.valueOf(eggcounter)+" ");

对于您的问题,您应该使用以下if语句:

 if (eggcounter < 9999998) {
      ImgButton.setImageResource(R.drawable.egg_2);
   }