標籤:
轉:http://www.jianshu.com/p/89687f618837
原因分析
當我們在Android依賴庫中使用switch-case語句訪問資源ID時會報如所示的錯誤,報的錯誤是case分支後面跟的參數必須是常數,換句話說出現這個問題的原因是Android library中產生的R.java中的資源ID不是常數:
開啟library中的R.java,發現確實如此,每一個資源ID都沒有被聲明為final:
但是當你開啟你的主工程,在onClick、onItemClick等各種回調方法中是可以通過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-fields
Tip
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
在Android library中不能使用switch-case語句訪問資源ID的原因分析及解決方案