在Android library中不能使用switch-case語句訪問資源ID的原因分析及解決方案

原因分析

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

library error
library error

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

library R.java
library R.java

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

??project中能夠通過switch-case語句正常引用資源ID:

project right
project right

??project中的R.java:

project R.java
project R.java

解決方案

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

library use
library use

參考資料:

??為了進一步了解問題的具體原因,在萬能的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

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • 原因分析??當我們在Android依賴庫中使用switch-case語句訪問資源ID時會報如下圖所示的錯誤,報的錯...
    cain07閱讀 739評論 0 2
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,915評論 18 139
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內(nèi)部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,765評論 18 399
  • 哈哈哈!今天的畫的也很簡單呢!希望大家會喜歡。 定位,頭的形狀,橢圓,稍微有點棱角。 眼睛的位置用十字大概畫出來,...
    吾棲夢閱讀 518評論 2 17
  • 我最近最想實現(xiàn)的目標是三個月內(nèi)收入增長一倍,并看到兒子具足智慧,學業(yè)有成。所以我咖啡冥想的內(nèi)容: 1.慷慨大度的種...
    葉景芳閱讀 183評論 1 2