非IF / ElSE的版本适用于SDK Build版本

时间:2018-08-06 13:10:20

标签: android if-statement toast

我使用此简单的条件检查来显示Toast,但未显示任何内容:

 public void ShowVersion(){

         //This works So I am sure the method is called:
         //Toast.makeText(this,"Method is called",Toast.LENGTH_LONG).show();

        if (Build.VERSION.SDK_INT >= 23) {
            Toast.makeText(this,"Version Supported",Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this,"Version not supported",Toast.LENGTH_LONG).show();
        }
    }

如果其他都不可行?

2 个答案:

答案 0 :(得分:0)

主要问题是IF块内的异常。异常中断IF / ELSE块。 try/catch块可以在类似情况下帮助发现问题。

答案 1 :(得分:-1)

尝试一下:

public void ShowVersion(){

     //This works So I am sure the method is called:
     //Toast.makeText(this,"Method is called",Toast.LENGTH_LONG).show();

    if (android.os.Build.VERSION.SDK_INT>=11) {
        Toast.makeText(this,"Version Supported",Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this,"Version not supported",Toast.LENGTH_LONG).show();
    }
}

或更优雅的方式是:

public void ShowVersion(){

     //This works So I am sure the method is called:
     //Toast.makeText(this,"Method is called",Toast.LENGTH_LONG).show();

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        Toast.makeText(this,"Version Supported",Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this,"Version not supported",Toast.LENGTH_LONG).show();
    }
}