Action Performed when Button Clicked n Times

你。 提交于 2019-12-02 14:53:27

问题


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
            }
        }
    });
}


来源:https://stackoverflow.com/questions/16652114/action-performed-when-button-clicked-n-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!