Pro Android學習筆記(四):瞭解Android資源(下)

來源:互聯網
上載者:User

處理任意的XML檔案

自訂的xml檔案放置在res/xml/下,可以通過R.xml.file_name來擷取一個XMLResourceParser對象。下面是xml檔案的例子:

<rootname="tom"><--也可以是<root>,本次採用帶參數的方式作為實驗--> 
   <leaf>Hello from an elementtest.</leaf>
   <leaf>Hello World!</leaf>
   <cornersradius="13dp"/>
</root>

通過javacode對xml檔案進行逐層解析,代碼如下:

try{  //防止在解析過程中,因xml檔案書寫或解析分析不匹配等原因造成的異常
   XmlPullParser xpp =getResources().getXml(R.xml.rt_test);
 //擷取XML資源的對象
            
   int eventType = xpp.next();  //相當於xpp.next(); int eventType =xpp.getEventType(),而next()直接傳回型別
   while(eventType != XmlPullParser.END_DOCUMENT){ //根據類型不同進行相應處理
       switch(eventType){ 
       caseXmlPullParser.START_DOCUMENT
           Log.d("xml","***************start****************"); 
           break; 
       caseXmlPullParser.START_TAG
           int count = xpp.getAttributeCount(); 
           Log.d("xml","starttap: " + xpp.getName() + "attribute number " +count); 
           for(int i = 0 ; i < count ; i ++){ //此處處理<xxxx yy=zz….>中yy=zz的參數部分,要注意xml是允許這樣編寫,除非確定自訂的XML的schema中不純正此方式
               Log.d("xml","    Attribute " + i + " : " + xpp.getAttributeName(i) +" = " +xpp.getAttributeValue(i)); 
           } 
           break; 
       caseXmlPullParser.END_TAG
           Log.d("xml","endtap: " + xpp.getName()); 
           break; 
       case XmlPullParser.TEXT
           Log.d("xml"," text: " + xpp.getText()); 
           break; 
       default: 
           Log.d("xml","eventType= " + eventType); 
           break; 
       } 
      eventType = xpp.next(); 
   } 
   Log.d("xml","***************end****************"); 
}catch(Throwable t){ 
   Log.e("xml","testXMLget exception t : " +t.getMessage()); 
}

更詳細的代碼說明可以閱讀Android學習筆記(三八):資源resource(上)、XML解析(XmlPullParser)。運行結果如下:

處理Raw資源

raw資源位於res/raw目錄下,和其他的資源不同,不經過編譯就打包到應用的apk中。raw檔案可以為音頻、視頻等任何格式的檔案。讀取是和java的檔案讀取一直,不同的是通過R.raw.filename來擷取。

protected void testRaw(){ 
   try{ //io讀取,對異常的擷取
       InputStream is =getResources().openRawResource(R.raw.rt_test); //擷取raw資源
       readTextFile(is);
       is.close();
   }catch(Throwable t){
       Log.e("raw","testRaw error : " + t.getMessage());
    }
}

private void readTextFile(InputStream is) throwsIOException{
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int ch =is.read();
    while(ch !=-1){
       baos.write(ch);
       ch =is.read();           
    }
   Log.d("raw",baos.toString());
   //Log.d("raw",newString(baos.toByteArray(),"GB2312"));
}

處理Asset資源

asset資源是位於/assets目錄下,該目錄於/res目錄平衡,即不在/res下面,所以不在R.java中形成相關的ID,不能通過ID來擷取asset資源。/assets是應用的使用者目錄,類似linux使用者中的~/目錄。我們在改目錄下放置文字檔tv_test.txt。下面是讀取的代碼。

protected void testAssets(){ 
    try{
       AssetManager am = getAssets(); //通過AssetManager來擷取/assets目錄下的檔案
       InputStream is =am.open("vt_test.txt");//不使用ID,直接通過檔案名稱來擷取,又如”subbir/vt_test2.txt”
       readTextFile(is);
       is.close();
   }catch(Throwable t){
       Log.e("asset","testAsset Resource error : " + t.getMessage());
    }
}

注意,getResource()和getAsset()都是activity下的方法,如activity.getResource()。

資源和配置的變更

資源有助於本地化,包括適配語言,橫/豎屏、屏尺寸等等。在res中出了之前介紹的default檔案夾,還可以有基於條件適配的檔案夾,存放相同名字的XML檔案,這些檔案夾在R.java中具有相同的ID。Android根據實際情況,選擇合適檔案夾中的XML描述。例如:

\res\layout\main_layout.xml
\res\layout-port\main_layout.xml
\res\layout-land\main_layout.xml

當裝置為豎屏時,則優先選擇layout-port,其次為layout。帶有條件的檔案夾成為alternate resources,所帶的條件,如上例子中的-port成為configuration qualifiers。這種帶適配條件檔案夾的格式為:預設資源檔夾名-條件1[-條件2[-條件N...]]。具體的configuration
qualifiers可以在:http://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources中尋找,下面列舉部分:

mccAAA: AAA is the mobile country code.
mncAAA: AAA is the carrier/network code.
en-rUS: Language and region.
sw<N>dp, w<N>dp, h<N>dp: Smallest width, available width, available height (since API 13).
small, normal, large, xlarge: Screen size.
long, notlong: Screen type.
port, land: Portrait or landscape.
car, desk: Type of docking.
night, notnight: Night or day.
ldpi, mdpi, hdpi, xhdpi, nodpi, tvdpi: Screen density.
notouch, stylus, finger: Kind of screen.
keysexposed, keyssoft, keyshidden: Kind of keyboard.
nokeys, qwerty, 12key: Number of keys.
navexposed, navhidden: Navigation keys hidden or exposed.
nonav, dpad, trackball, wheel: Type of navigation device.
v3, v4, v7: API level.

這些條件是有優先順序別的,在預設資源檔夾名-條件1[-條件2[-條件N...]]中條件1的優先順序別必須高於條件2的優先順序別,同理條件2的優先順序別必須高於條件3的優先順序別。條件層級的高低是Android預先設定的,上面列舉的各條件的優先順序別就是從高到低。例如有以下的幾個檔案夾:/res/values,/res/values-en,/res/values-en-rUS,/res/values-port,/res/values-en-port。對於語言為美國英語(en-rUS)的豎屏情況下,Android通過ID尋找資源的順序為/res/values-en-rUS,/res/values-en-port,/res/values-en,/res/values-port,/res/values。

相關連結:
我的Android開發相關文章

聯繫我們

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