Action Performed when Button Clicked n Times

2019-03-04 05:50发布

问题:

public void boss(final Boss boss) {
    forward.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            boss.setHp(boss.getHp() - 1);
            log("" + boss.getHp());
        }
    });
    if(boss.getHp() > 0){
        boss(boss);
    }
}

So, in the above code, I am trying to have bossHp reduce by 1 every time forward is clicked. There is a stackoverflow error with the code. (It is just calling boss() in an infinite loop.) How can I have it keep reducing bossHp by 1 every time the user clicks forward, and then stop when bossHp <= 0?

Note: Button forward is used elsewhere, too.

Thanks!

EDIT: Sorry about that typo earlier! the code shown is now the correct code. Any ideas? Thanks!

CLARIFICATION:

What I want to have happen, is it checks bossHp every time Button forward is clicked UNTIL bossHp <= 0. At which point I want to exit the method, but not before then

回答1:

This should work. Also you don't have to pass boss as function parameter. You can keep that object as field in your class.

public void boss(final Boss boss) {
    forward.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if(boss.getHp() > 0){
                boss.setHp(boss.getHp() - 1);
                log("" + boss.getHp());
            } else {
                //boss is dead
            }
        }
    });
}