原因分析
??當我們在Android依賴庫中使用switch-case語句訪問資源ID時會報如下圖所示的錯誤孤里,報的錯誤是case分支后面跟的參數(shù)必須是常數(shù),換句話說出現(xiàn)這個問題的原因是Android library中生成的R.java中的資源ID不是常數(shù):

??打開library中的R.java氮块,發(fā)現(xiàn)確實如此拔稳,每一個資源ID都沒有被聲明為final:

??但是當你打開你的主工程,在onClick、onItemClick等各種回調(diào)方法中是可以通過switch-case語句來訪問資源ID的要拂,因為在主工程的R.java中資源ID都被聲明為了final常量抠璃。
??project中能夠通過switch-case語句正常引用資源ID:

??project中的R.java:

解決方案
??既然是由于library的R.java中的資源ID不是常量引起的,我們可以在library中通過if-else-if條件語句來引用資源ID脱惰,這樣就避免了這個錯誤:

參考資料:
??為了進一步了解問題的具體原因搏嗡,在萬能的StackOverflow上還真搜到了這個問題:
In a regular Android project, constants in the resource R class are declared like this:
public static final int main=0x7f030004;
However, as of ADT 14, in a library project, they will be declared like this:
public static int main=0x7f030004;
In other words, the constants are not final in a library project. Therefore your code would no longer compile.
The solution for this is simple: Convert the switch statement into an if-else statement.
public void onClick(View src)
{
int id = src.getId();
if (id == R.id.playbtn){
checkwificonnection();
} else if (id == R.id.stopbtn){
Log.d(TAG, "onClick: stopping srvice");
Playbutton.setImageResource(R.drawable.playbtn1);
Playbutton.setVisibility(0); //visible
Stopbutton.setVisibility(4); //invisible
stopService(new Intent(RakistaRadio.this,myservice.class));
clearstatusbar();
timer.cancel();
Title.setText(" ");
Artist.setText(" ");
} else if (id == R.id.btnmenu){
openOptionsMenu();
}
}
http://tools.android.com/tips/non-constant-fieldsTip
You can quickly convert a switch statement to an if-else statement using Eclipse's quick fix.Click on the switch keyword and press Ctrl + 1 then select
Convert 'switch' to 'if-else'.
??問題詳見:switch case statement error: case expressions must be constant expression