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

轉:http://www.jianshu.com/p/89687f618837java

緣由分析

  當咱們在Android依賴庫中使用switch-case語句訪問資源ID時會報以下圖所示的錯誤,報的錯誤是case分支後面跟的參數必須是常數,換句話說出現這個問題的緣由是Android library中生成的R.java中的資源ID不是常數:android

打開library中的R.java,發現確實如此,每個資源ID都沒有被聲明爲final:express

可是當你打開你的主工程,在onClick、onItemClick等各類回調方法中是能夠經過switch-case語句來訪問資源ID的,由於在主工程的R.java中資源ID都被聲明爲了final常量。ui

  project中可以經過switch-case語句正常引用資源ID:this

project中的R.java:code

解決方案

  既然是因爲library的R.java中的資源ID不是常量引發的,咱們能夠在library中經過if-else-if條件語句來引用資源ID,這樣就避免了這個錯誤:blog

參考資料:

  爲了進一步瞭解問題的具體緣由,在萬能的StackOverflow上還真搜到了這個問題:ip

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:get

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

相關文章
相關標籤/搜索