简体   繁体   中英

Why the if statement doesn't work in an Image button?

Hello Guys im new on this Website so if I make any mistakes please forgive me. For the School I need to code an App and I want to code an app like the old Egg app where you needed to click on for like 1.000.000 times.

My Counter works but I wanted to let the Egg break. For this I wanted to use an if statement so I can make it break after like 200 times and so on.

My Problem is that if I'm pressing the button the Image switch in the first time. Not as I expected in the third time

Do anyone knows what my problem is?

PS: I'm new in java so maybe the code isn't sexy

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 + " ");

    }

The first time you click on the button, the 'eggcounter' is at 999999.
That is more than 999998, so the if statement is true, thus the image is changed.

I'm guessing that you should change the '>' to a '<' so the image isn't changed until the 3rd click.

First of all , you . setText() method isn't correct ,you should use it like that :

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

and for your issue you should use your if statement like this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM