在代碼中使用資源

來源:互聯網
上載者:User

在代碼中使用資源

 

你可以在代碼中通過R靜態類使用資源。R靜態類是基於你的外部資源由工程編譯自動建立的。在R類中,它為每種資源類型建立靜態子類,且必須至少有一個資源。例如,預設建立的新工程包含R.string和R.drawable子類。

 

如果你在Eclipse中使用ADT外掛程式的話,當你對外部資源檔或檔案夾所做的任何改變都會引發R類的自動建立。如果你沒有使用外掛程式,可以使用AAPT工具去編譯工程產生R類。R是編譯產生的類,所以,你不要對它做任何的手動更改,當檔案重建的時候,你所做的更改就會丟失。

 

R中的每一個子類與資源關聯,子類中的變數名與資源標識一致——例如,R.string.app_name和R.drawable.icon。

 

這些變數的值資源在資源表中相應的位置,不是資源本身的執行個體。

 

在建構函式或方法(如setContentView)接受資源標識的地方,你可以傳入資源變數,如下面的程式碼片段所示:

 

// Inflate a layout resource.

setContentView(R.layout.main);

// Display a transient dialog box that displays the

// error message string resource.

Toast.makeText(this, R.string.app_error, Toast.LENGTH_LONG).show();

 

當你需要資源本身的執行個體的時候,你需要使用輔助方法從資源表(資源類的執行個體)中提取它們。

 

由於這些方法要搜素應用程式的資源表,所以這些輔助方法不能是靜態。在你的應用程式上下文中,使用getResources方法來獲得應用程式的資源執行個體,如下代碼所示:

 

Resources myResources = getResources();

 

資源類為每一種可獲得的資源類型提供了get方法,並且只需要傳遞你想要獲得資源執行個體的標識。下面的程式碼片段給出了通過輔助方法如何獲得資源值:

 

Resources myResources = getResources();

CharSequence styledText = myResources.getText(R.string.stop_message);

Drawable icon = myResources.getDrawable(R.drawable.app_icon);

 

int opaqueBlue = myResources.getColor(R.color.opaque_blue);

 

float borderWidth = myResources.getDimension(R.dimen.standard_border);

 

Animation tranOut;

tranOut = AnimationUtils.loadAnimation(this, R.anim.spin_shrink_fade);

 

String[] stringArray;

stringArray = myResources.getStringArray(R.array.string_array);

 

int[] intArray = myResources.getIntArray(R.array.integer_array);

 

Frame-by-Frame 動畫資源存放在AnimationResources中,你可以通過getDrawable方法返回並轉換傳回值如下:

 

AnimationDrawable rocket;

rocket = (AnimationDrawable)myResources.getDrawable(R.drawable.frame_by_frame);

 

AnimationDrawable 類在載入時,存在一個bug。目前,AnimationDrawable 的資源在Activity的onCreate方法執行結束後的一些時間之前不能正確地載入。目前可用的方法是在載入Frame-by-Frame資源之前使用定時器強制進行延時。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.