Android之Resource介紹和使用

轉自http://android.blog.51cto.com/268543/302529/ 

Android Resource介紹和使用
2010-04-21 21:54:01
原創作品,允許轉載,轉載時請務必以超鏈接形式標明文章 原始出處 、作者信息和本聲明。否則將追究法律責任。http://android.blog.51cto.com/268543/302529

 1. 相關文件夾介紹

     在Android項目文件夾裏面,主要的資源文件是放在res文件夾裏面的。assets文件夾是存放不進行編譯加工的原生文件,即該文件夾裏面的文件不會像xml,java文件被預編譯,可以存放一些圖片,html,js, css等文件。在後面會介紹如何讀取assets文件夾的資源!
     res文件夾裏面的多個文件夾的各自介紹(來自網上的Android開發指南中文版內容):

目錄Directory

資源類型Resource Types

res/anim/

XML文件,它們被編譯進逐幀動畫(frame by frame animation)或補間動畫(tweened animation)對象

res/drawable/

.png、.9.png、.jpg文件,它們被編譯進以下的Drawable資源子類型中:

要獲得這種類型的一個資源,可以使用Resource.getDrawable(id)

位圖文件

9-patches(可變尺寸的位圖)

爲了獲取資源類型,使用mContext.getResources().getDrawable(R.drawable.imageId)

注意:放在這裏的圖像資源可能會被aapt工具自動地進行無損壓縮優化。比如,一個真彩色但並不需要256色的PNG可能會被轉換爲一個帶調色板的8位PNG。這使得同等質量的圖片佔用更少的資源。所以我們得意識到這些放在該目錄下的二進制圖像在生成時可能會發生變化。如果你想讀取一個圖像位流並轉換成一個位圖(bitmap),請把圖像文件放在res/raw/目錄下這樣可以避免被自動優化。

res/layout/

被編譯爲屏幕布局(或屏幕的一部分)的XML文件。參見佈局聲明(Declaring Layout)

res/values/

可以被編譯成很多種類型的資源的XML文件。

注意: 不像其他的res/文件夾,它可以保存任意數量的文件,這些文件保存了要創建資源的描述,而不是資源本身。XML元素類型控制這些資源應該放在R類的什麼地方。

儘管這個文件夾裏的文件可以任意命名,不過下面使一些比較典型的文件(文件命名的慣例是將元素類型包含在該名稱之中):

      array.xml 定義數組

     colors.xml 定義color drawable顏色的字符串值(color string values)。使用Resource.getDrawable()和Resources.getColor()分別獲得這些資源。

     dimens.xml定義尺寸值(dimension value)。使用Resources.getDimension()獲得這些資源。

      strings.xml定義字符串(string)值。使用Resources.getString()或者Resources.getText()獲取這些資源。getText()會保留在UI字符串上應用的豐富的文本樣式。

      styles.xml 定義樣式(style)對象。

res/xml/

任意的XML文件,在運行時可以通過調用Resources.getXML()讀取。

res/raw/

直接複製到設備中的任意文件。它們無需編譯,添加到你的應用程序編譯產生的壓縮文件中。要使用這些資源,可以調用Resources.openRawResource(),參數是資源的ID,即R.raw.somefilename

 

2.自動生成的R class

     在項目文件夾的gen文件夾裏面有個R.java,我們平常引用的資源主要引用這個類的變量。
 
     注意:R類是自動生成的,並且它不能被手動修改。當資源發生變動時,它會自動修改。
 

3. 在代碼中使用資源

下面是一個引用資源的語法:
R.resource_type.resource_name  或者 android.R.resource_type.resource_name
 
其中resource_type是R的子類,保存資源的一個特定類型。resource_name是在XML文件定義的資源的name屬性,或者有其他文件類型爲資源定義的文件名(不包含擴展名,這指的是drawable文件夾裏面的icon.png類似的文件,name=icon)。 Android包含了很多標準資源,如屏幕樣式和按鈕背景。要在代碼中引用這些資源,你必須使用android進行限定,如android.R.drawable.button_background
 
下面是官方給出的一些在代碼中使用已編譯資源的正確和錯誤用法的例子:
  1. // Load a background for the current screen from a drawable resource. 
  2. this.getWindow().setBackgroundDrawableResource(R.drawable.my_background_image); 
  3.  
  4. // WRONG Sending a string resource reference into a  
  5. // method that expects a string. 
  6. this.getWindow().setTitle(R.string.main_title); 
  7.  
  8. // RIGHT Need to get the title from the Resources wrapper. 
  9. this.getWindow().setTitle(Resources.getText(R.string.main_title)); 
  10.  
  11. // Load a custom layout for the current screen. 
  12. setContentView(R.layout.main_screen); 
  13.  
  14. // Set a slide in animation for a ViewFlipper object. 
  15. mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,  
  16.         R.anim.hyperspace_in)); 
  17.  
  18. // Set the text on a TextView object. 
  19. TextView msgTextView = (TextView)findViewByID(R.id.msg); 
  20. msgTextView.setText(R.string.hello_message);  
       查了SDK Doc,才明白爲什麼window.setTitle要先Resources.getText,原來setTitle的參數是CharSequence,Resources.getText(int)返回的是CharSequence;而其他setText的參數有的是CharSequence,有的是int(這就是Resources變量值)。
 
同時官方還給了兩個使用系統資源的例子:
  1. //在屏幕上顯示標準應用程序的圖標
  2. public class MyActivity extends Activity { 
  3.     public void onStart() { 
  4.         requestScreenFeatures(FEATURE_BADGE_IMAGE); 
  5.         super.onStart(); 
  6.         setBadgeResource(android.R.drawable.sym_def_app_icon); 
  7.     } 
  8.  
  9. //應用系統定義的標準"綠色背景"視覺處理 
  10. public class MyActivity extends Activity 
  11.     public void onStart() { 
  12.         super.onStart(); 
  13.         setTheme(android.R.style.Theme_Black); 
  14.     } 
 

4. xml文件內引用資源

1) 引用自定義的資源
       android:text="@string/hello"
       這裏使用"@"前綴引入對一個資源的引用--在@[package:]type/name形式中後面的文本是資源的名稱。在這種情況下,我們不需要指定包名,因爲我們引用的是我們自己包中的資源。type是xml子節點名,name是xml屬性名:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.     <string name="hello">Hello World, HelloDemo!</string> 
  4. </resources> 
 
2) 引用系統資源
       android:textColor="@android:color/opaque_red"   指定package: android
 
3) 引用主題屬性
        另外一種資源值允許你引用當前主題中的屬性的值。這個屬性值只能在樣式資源和XML屬性中使用;它允許你通過將它們改變爲當前主題提供的標準變化來改變UI元素的外觀,而不是提供具體的值。
        android:textColor="?android:textDisabledColor"
    
        注意,這和資源引用非常類似,除了我們使用一個"?"前綴代替了"@"。當你使用這個標記時,你就提供了屬性資源的名稱,它將會在主題中被查找--因爲資源工具知道需要的屬性資源,所以你不需要顯示聲明這個類型(如果聲明,其形式就是?android:attr/android:textDisabledColor)。除了使用這個資源的標識符來查詢主題中的值代替原始的資源,其命名語法和"@"形式一致:?[namespace:]type/name,這裏類型可選。
 

5. 替換資源(爲了可替換的資源和配置)

    個人理解這個替換資源主要用於適應多種規格的屏幕,以及國際化。對於這部分的內容,請參考http://androidappdocs.appspot.com/guide/topics/resources/resources-i18n.html,以後再研究! 
 

6. Color Value

語法:
  1. <color name="color_name">#color_value</color> 
可以保存在res/values/colors.xml (文件名可以任意)。
xml引用:android:textColor="@color/color_name"
Java引用: int color = Resources.getColor(R.color.color_name)
 
其中#color_value有以下格式(A代表Alpha通道):
#RGB
#ARGB
#RRGGBB
#AARRGGBB
 
xml示例(聲明兩個顏色,第一個不透明,第二個透明色):
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.     <color name="opaque_red">#f00</color> 
  4.     <color name="translucent_red">#80ff0000</color> 
  5. </resources> 
 

7.Color Drawables

語法:
  1. <drawable name="color_name">color_value</drawable> 
可以保存在res/values/colors.xml。
xml引用:android:background="@drawable/color_name"
java引用:Drawable redDrawable = Resources.getDrawable(R.drawable.color_name)
 
color_name和上面的一樣。個人認爲,一般情況下使用color屬性,當需要用到paintDrawable時才使用drawable屬性。
 
xml示例:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.     <drawable name="opaque_red">#f00</drawable> 
  4.     <drawable name="translucent_red">#80ff0000</drawable> 
  5. </resources> 
 

8. 圖片

      一般放在res/drawable/裏面。官方提示png (preferred), jpg (acceptable), gif (discouraged),看來一般使用png格式比較好!
xml引用  @[package:]drawable/some_file
java引用 R.drawable.some_file     引用是不帶擴展名
 

9. dimension

語法:
  1. <dimen name="dimen_name">dimen_value單位</dimen> 
一般保存爲res/values/dimen.xml。
度量單位:
px(象素): 屏幕實際的象素,常說的分辨率1024*768pixels,就是橫向1024px, 縱向768px,不同設備顯示效果相同。
 
in(英寸): 屏幕的物理尺寸, 每英寸等於2.54釐米。
 
mm(毫米): 屏幕的物理尺寸。
 
pt(點)  : 屏幕的物理尺寸。1/72英寸。
 
dp/dip  : 與密度無關的象素,一種基於屏幕密度的抽象單位。在每英寸160點的顯示器上,1dp = 1px。但dp和px的比例會隨着屏幕密度的變化而改變,不同設備有不同的顯示效果。設置寬度或者高度等屬性時,推薦使用dp(dip)作爲單位
 
sp      : 與刻度無關的象素,主要用於字體顯示best for textsize,作爲和文字相關大小單位。
 
XML: android:textSize="@dimen/some_name"
Java: float dimen = Resources.getDimen(R.dimen.some_name)
 
xml示例:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.     <dimen name="one_pixel">1px</dimen> 
  4.     <dimen name="double_density">2dp</dimen> 
  5.     <dimen name="sixteen_sp">16sp</dimen> 
  6. </resources> 
 

10. string

下面是官方給出的正確/錯誤的例子:
  1. //不使用轉義符則需要用雙引號包住整個string 
  2. <string name="good_example">"This'll work"</string> 
  3.  
  4. //使用轉義符 
  5. <string name="good_example_2">This\'ll also work</string> 
  6.  
  7. //錯誤 
  8. <string name="bad_example">This won't work!</string> 
  9.  
  10. //錯誤 不可使用html轉義字符 
  11. <string name="bad_example_2">XML encodings won&apos;t work either!</string> 
     對於帶格式的string,例如在字符串中某些文字設置顏色,可以使用html標籤。對於這類型的string,需要進行某些處理,在xml裏面不可以被其他資源引用。官方給了一個例子來對比普通string和帶格式string的使用:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.     <string name="simple_welcome_message">Welcome!</string> 
  4.     <string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string> 
  5. </resources> 
Xml代碼
  1. <TextView 
  2.     android:layout_width="fill_parent" 
  3.     android:layout_height="wrap_content" 
  4.     android:textAlign="center" 
  5.     android:text="@string/simple_welcome_message"/> 
Java代碼
  1. // Assign a styled string resource to a TextView on the current screen. 
  2. CharSequence str = getString(R.string.styled_welcome_message); 
  3. TextView tv = (TextView)findViewByID(R.id.text); 
  4. tv.setText(str); 
    另外對於帶風格/格式的string的處理,就麻煩一點點。官方給了一個例子:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.   <string name="search_results_resultsTextFormat">%1$d results for &lt;b>&amp;quot;%2$s&amp;quot;&lt;/b></string> 
  4. </resources> 
這裏的%1$d是個十進制數字,%2$s是字符串。當我們把某個字符串賦值給%2$s之前,需要用htmlEncode(String)函數處理那個字符串:
  1. //title是我們想賦值給%2$s的字符串 
  2. String escapedTitle = TextUtil.htmlEncode(title); 
 然後用String.format() 來實現賦值,接着用fromHtml(String) 得到格式化後的string:
  1. String resultsTextFormat = getContext().getResources().getString(R.string.search_results_resultsTextFormat); 
  2. String resultsText = String.format(resultsTextFormat, count, escapedTitle); 
  3. CharSequence styledResults = Html.fromHtml(resultsText); 
 

11. assets文件夾資源的訪問

       assets文件夾裏面的文件都是保持原始的文件格式,需要用AssetManager以字節流的形式讀取文件。
      1. 先在Activity裏面調用getAssets()來獲取AssetManager引用。
      2. 再用AssetManager的open(String fileName, int accessMode)方法則指定讀取的文件以及訪問模式就能得到輸入流InputStream。 
      3. 然後就是用已經open file 的inputStream讀取文件,讀取完成後記得inputStream.close()
      4.調用AssetManager.close()關閉AssetManager。
 
    至於style and theme,Layout,動畫Animation,Menu則查看本博客的其他文章。附上官方的相應介紹網址http://androidappdocs.appspot.com/guide/topics/resources/available-resources.html
    另外,官方還介紹了icon design的Guidelineshttp://androidappdocs.appspot.com/guide/practices/ui_guidelines/icon_design.html

本文出自 “學習Android” 博客,請務必保留此出處http://android.blog.51cto.com/268543/302529

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章