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

來源:互聯網
上載者:User

標籤:

轉: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的原因分析及解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.