简体   繁体   中英

How can I put OnClickListener inside IF Statement?

I'm a beginner in Android Development. I'm creating a game like 4 pics 1 word. My code is not yet complete. My problem is, that I can't put an OnClickListener inside an IF Statement.

I need to randomize the questions so I put random generator then use if statements to present the question that is given by the random number. I use for loop so that the game will not end until all the games have been played. Here's my code in my

MainActivity :

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    Button btnStart;

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

        btnStart = (Button) findViewById(R.id.btnStart);
        btnStart.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btnStart:
                startActivity(new Intent(this, game.class));
                break;
        }
    }
}

Game :

public class game extends AppCompatActivity{
    EditText etAnswer;
    Button btnSubmit;
    ImageView image1;
    ImageView image2;
    ImageView image3;
    ImageView image4;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        etAnswer = (EditText) findViewById(R.id.etAnswer);
        image1 = (ImageView) findViewById(R.id.image1);
        image2 = (ImageView) findViewById(R.id.image2);
        image3 = (ImageView) findViewById(R.id.image3);
        image4 = (ImageView) findViewById(R.id.image4);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);

        ArrayList<Integer> imageList = new ArrayList<>();
        imageList.add(R.drawable.andresbonifacio1);
        for (int i = 0; i >= imageList.size(); i++) {
            Random generator = new Random();
            int number = generator.nextInt(5) + 1;

            if (number == 1) {
                image1.setImageResource(R.drawable.andresbonifacio1);
                    new GameData().questionOne();
            } else if (number == 2) {
                image1.setImageResource(R.drawable.andresbonifacio1);
                        new GameData().questionTwo();
            } else if (number == 3) {
                image1.setImageResource(R.drawable.andresbonifacio1);
                        new GameData().questionThree();
            } else if (number == 4) {
                image1.setImageResource(R.drawable.andresbonifacio1);
                        new GameData().questionFour();
            } else {
                image1.setImageResource(R.drawable.andresbonifacio1);
                        new GameData().questionFive();
            }
        }
    }
}

And here's my code in the GameData

public class GameData extends game{

    public void questionOne() {
        image1.setImageResource(R.drawable.andresbonifacio1);
        String answer = etAnswer.getText().toString();
        if (answer.equals("Jose Rizal") || answer.equals("jose rizal") || answer.equals("Rizal") || answer.equals("rizal")) {
            AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
            dlgAlert.setMessage("The famous Rizal monument in Luneta was not the work of a Filipino but a Swiss sculptor named Richard Kissling?" +
                    "\n" +
                    "\n" +
                    "Source: http://www.joserizal.ph/ta01.html");
            dlgAlert.setTitle("Did you know that ...");
            dlgAlert.setPositiveButton("Next",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //statements
                            new game();
                        }
                    });
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
            new game();

        } else {
            Context context = getApplicationContext();
            CharSequence text = "Wrong! Try Again.";
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    }


    public void questionTwo() {
        String answer = etAnswer.getText().toString();
        if (answer.equals("Antonio Luna") || answer.equals("antonio luna") || answer.equals("Heneral Luna") || answer.equals("heneral luna")) {
            AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
            dlgAlert.setMessage("He is the younger brother of the famous Filipino painter Juan Luna who is known for his masterpiece Spoliarium." +
                    "\n" +
                    "\n" +
                    "Source: http://nobert-bermosa.blogspot.com/2011/05/70-interesting-facts-about-general.html");
            dlgAlert.setTitle("Did you know that ...");
            dlgAlert.setPositiveButton("Next",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            new game();
                        }
                    });
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
            new game();

        } else {
            Context context = getApplicationContext();
            CharSequence text = "Wrong! Try Again.";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    }

    public void questionThree() {
        String answer = etAnswer.getText().toString();
        if (answer.equals("Apolinario Mabini") || answer.equals("Mabini") || answer.equals("apolinario mabini") || answer.equals("mabini")) {
            AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
            dlgAlert.setMessage("His complete name is Apolinario Marana Mabini and was nicknamed Poly." +
                    "\n" +
                    "\n" +
                    "Source: http://nobert-bermosa.blogspot.com/2011/04/50-interesting-facts-about-apolinario.html");
            dlgAlert.setTitle("Did you know that ...");
            dlgAlert.setPositiveButton("Next",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            new game();
                        }
                    });
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
            new game();

        } else {
            Context context = getApplicationContext();
            CharSequence text = "Wrong! Try Again.";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    }

    public void questionFour() {
        String answer = etAnswer.getText().toString();
        if (answer.equals("Melchora Aquino") || answer.equals("melchora aquino") || answer.equals("Tandang Sora") || answer.equals("tandang sora")) {
            AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
            dlgAlert.setMessage("She had a talent in singing and was very well known for singing at the mass. She was also often chosen for the role of “Reyna Elena” during the Santacruzan. " +
                    "\n" +
                    "\n" +
                    "Source: biography.yourdictionary.com");
            dlgAlert.setTitle("Did you know that ...");
            dlgAlert.setPositiveButton("Next",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            new game();
                        }
                    });
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
            new game();

        } else {
            Context context = getApplicationContext();
            CharSequence text = "Wrong! Try Again.";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
    }
}

public void questionFive() {
    String answer = etAnswer.getText().toString();
            if(answer.equals("Andres Bonifacio") ||  answer.equals("andres bonifacio")){
                AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
                dlgAlert.setMessage("It was a secret society after all. The final test to be a Katipunero was a blood compact (sandugo) " +
                        "reminiscent of the first one Filipinos shared with the Spaniards early in history. It was the Katipunan’s way of " +
                        "capturing the narrative from the “traitors” and making brotherhood their own." +
                        "But the twist to the Katipunan’s sandugo was that they wrote their oath in their own blood. After this, " +
                        "they chose a symbolic name for themselves. Quite interesting was the Supremo’s choice of name, and quite " +
                        "telling too, for a leader of a hopeful nation: MAYPAG-ASA." +
                        "\n" +
                        "\n" +
                        "http://www.rappler.com/nation/44920-andres-bonifacio-myths-trivia-execution");
                dlgAlert.setTitle("Did you know that ...");
                dlgAlert.setPositiveButton("Next",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                new game();
                            }
                        });
                dlgAlert.setCancelable(true);
                dlgAlert.create().show();
                new game();

            }else{
                Context context = getApplicationContext();
                CharSequence text = "Wrong! Try Again.";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
    }}

Why are you putting onClickListener in if-else block?

What you can do is put if-else block inside onClickListener . Something like this,

youtButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
       if(..)
          ...
       else .... 
    }
});

Set button OnClickListener as anonymous class. Try this code:

    public class MainActivity extends AppCompatActivity{
            Button btnStart;

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

                btnStart = (Button) findViewById(R.id.btnStart);
                btnStart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //insert your condition here
                        startActivity(new Intent(this, game.class));
                    }
                });
            }


        }

Hope this help you.

Also, U can simplify code:

findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener() { ... })

Update: U may implement calling specified method after start activity like this:

Intent intent = new Intent(context, game.class);
intent.putExtra("startFuncOne", true);
startActivity(intent); 

And then in your Game activity:

if (getIntent().getBooleanExtra("startFuncOne", false)) {
   functionOne();
}

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