android 從assets和res中讀取檔案

來源:互聯網
上載者:User

標籤:

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_filejava引用 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的比例會隨著螢幕密度的變化而改變,不同裝置有不同的顯示效果。  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。需要注意的是,來自Resources和Assets 中的檔案只可以讀取而不能進行寫的操作
以下為從Raw檔案中讀取:
代碼
    public String getFromRaw(){ 
            try { 
                InputStreamReader inputReader = new InputStreamReader( getResources().openRawResource(R.raw.test1));
                BufferedReader bufReader = new BufferedReader(inputReader);
                String line="";
                String Result="";
                while((line = bufReader.readLine()) != null)
                    Result += line;
                return Result;
            } catch (Exception e) { 
                e.printStackTrace(); 
            }             
    } 
以下為直接從assets讀取
代碼
    public String getFromAssets(String fileName){ 
            try { 
                 InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) ); 
                BufferedReader bufReader = new BufferedReader(inputReader);
                String line="";
                String Result="";
                while((line = bufReader.readLine()) != null)
                    Result += line;
                return Result;
            } catch (Exception e) { 
                e.printStackTrace(); 
            }
    } 
當然如果你要得到記憶體流的話也可以直接返回記憶體流! 本文來自 http://blog.sina.com.cn/s/blog_7161d18a0100o7go.html

 

  

android 從assets和res中讀取檔案(轉)

聯繫我們

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