make if if只检查一个命令

时间:2013-11-15 13:11:16

标签: java android button if-statement

我有一个ViewFlipper和一个下一个按钮,我想在检查并执行一个命令后停止按钮 我希望它停止检查其余的,除非我再次点击它

我的代码:

    Next.setOnClickListener(new View.OnClickListener() {
            ViewFlipper flipp = (ViewFlipper) findViewById(R.id.flipp);
        @Override
        public void onClick(View view) {

            if(flipp.getDisplayedChild() == 0){if(qOne.isChecked()) {CorrectToast();}else{WrongToast();}} 
            if(flipp.getDisplayedChild() == 1){if(qTwo.isChecked()){CorrectToast();}else{WrongToast();}}
            if(flipp.getDisplayedChild() == 2){if(qThree.isChecked()){CorrectToast();}else{WrongToast();}}
            if(flipp.getDisplayedChild() == 3){if(qFour.isChecked()){CorrectToast();}else{WrongToast();}}
        }
    });

4 个答案:

答案 0 :(得分:2)

改为使用switch语句:

Next.setOnClickListener(new View.OnClickListener() {
        ViewFlipper flipp = (ViewFlipper) findViewById(R.id.flipp);
    @Override
    public void onClick(View view) {
        switch(flipp.getDisplayedChild()) {
            case 0: if(qOne.isChecked()) {CorrectToast();}else{WrongToast();} break; 
            case 1: if(qTwo.isChecked()) {CorrectToast();}else{WrongToast();} break;
            case 2: if(qThree.isChecked()) {CorrectToast();}else{WrongToast();} break;
            case 3: if(qFour.isChecked()) {CorrectToast();}else{WrongToast();} break;
            default: break; //do default action,
        }
    }  

答案 1 :(得分:1)

使用if () else if ()构造

答案 2 :(得分:1)

您可以像这样使用if() { } else if() { }语句

    Next.setOnClickListener(new View.OnClickListener() {
            ViewFlipper flipp = (ViewFlipper) findViewById(R.id.flipp);
        @Override
        public void onClick(View view) {

            if(flipp.getDisplayedChild() == 0){if(qOne.isChecked()) {CorrectToast();}else{WrongToast();}} 
            else if(flipp.getDisplayedChild() == 1){if(qTwo.isChecked()){CorrectToast();}else{WrongToast();}}
            else if(flipp.getDisplayedChild() == 2){if(qThree.isChecked()){CorrectToast();}else{WrongToast();}}
            else if(flipp.getDisplayedChild() == 3){if(qFour.isChecked()){CorrectToast();}else{WrongToast();}}
        }
    });

答案 3 :(得分:0)

switch语句没问题,但我建议这样做。它更具可读性,你可以添加更少的文章和混乱的对象。

public void onClick(View view) {
    CheckedObject[] objectsToCheck = new CheckedObject[]{qOne,qTwo,qThree,qFour};
    int index = flipp.getDisplayedChild();
    if (objectsToCheck[index].isChecked())
    {
         CorrectToast();
    }
    else 
    {
         WrongToast();
    }
}