天天看點

android中的資源通路

一.android中的資源是在代碼中使用的外部檔案。圖檔,音頻,動畫和字元串等叫做android中的資源檔案。 

二.Android工程 資源類型布局表

與src源檔案夾并列的兩個檔案夾assets和res用來儲存資源檔案。 

1.assets檔案夾中放原聲檔案如MP3檔案,通過AssetManager類以二進制流的形式通路 

2.res中資源可以通過R資源類直接通路: 

anim:儲存動畫 

drawable:位圖檔案 

layout:xml布局檔案 

values:各種xml資源檔案 

arrays.xml:xml數組檔案 

colors.xml:xml顔色檔案 

dimens.xml:xml尺寸檔案 

styles.xml:xml樣式檔案 

raw:直接複制到裝置中的源檔案 

menu:xml菜單檔案

使用mContext.getResources()得到Resources對象來擷取資源

XML的寫法如下:

代碼  

一個android工程中,有各種類型的資源檔案,大緻可以分為以下幾種:  

、  顔色 #RGB #ARGB #RRGGBB #AARRGGBB  

顔色資源應該位于<resourses></resourses>标簽下  

路徑res/values/colors.xml 名字可以随意  

定義<color name=”cname”>value</color> 

使用 Resourse.getValues.getColor  

<?xml version="1.0" encoding="utf-8"?> 

<resources> 

<color name="white">#FFFFFF</color> 

<color name="black">#000000</color> 

</resources> 

、  字串  

字串資源應該位于<resourses></resourses>标簽下  

路徑res/values/strings.xml  

定義<String  name=”sname”>value</String> 

使用 Resourse.getValues.getString  

    <string name="hello">Hello World, ResrouseTestActivity!</string> 

    <string name="app_name">ResrouseTest</string> 

、  圖檔  

圖檔資源一般使用png格式,使用其他格式的會出現各種問題,貌似不支援gif格式的圖檔,可是使用Movie來播放gif格式的圖檔  

路徑res/drawable  

可以直接存放圖檔也可以是xml等配置檔案(一般用于自定義元件)  

使用 getDrawable  

、  圖檔的顔色  

位于res/values/my_drawable.xml名字随意  

 <?xml version="1.0" encoding="utf-8"?> 

<drawable name="solid_red">#FF0000</drawable> 

定義用于填充一個元件的顔色值,即給view設定背景色。用法和drawable下的圖檔一樣,其實沒多少意義,使用顔色定義就ok了,目前我是這樣認為的,可能有更好的優點,不過我沒發現罷了,嘿嘿,continue...  

、  機關資源  

機關資源應該位于<resourses></resourses>标簽下  

路徑res/values/dimen.xml 名字可以随意  

使用和String、color類似  

<dimen name="dimen_name">2px</dimen> 

<dimen name="dimen_px">5px</dimen> 

<dimen name="dimen_pt">3pt</dimen> 

<dimen name="dimen_dp">3dp</dimen> 

、  Nine-patch(可以拉伸的小圖檔)  

支援圖檔的拉伸  

   貌似就是所謂的png圖檔檔案資源,圖檔在應用view的背景時,如果被設為background則會随view的大小變化做相應的拉伸和收縮,像ImageView這類設定src圖檔則不随view變化,按其自身大小顯示部分或全部!  

、  菜單  

菜單即可以從代碼中實作也可以在資源檔案中配置,這裡就是要描述一下第二種<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android">    <item           android:id="@+id/previous"           android:title="@string/previous"           android:enabled="false"  android:icon="@android:drawable/ic_media_previous"/>        <item           android:id="@+id/play_pause"           android:title="@string/play"           android:icon="@android:drawable/ic_media_play"/>    <item           android:id="@+id/next"           android:title="@string/next"           android:icon="@android:drawable/ic_menu_next"/></menu>8、  Layout布局  

這個就是你經常看到的與使用者互動的界面的xml檔案,就是各個view的排列和嵌套,沒什麼好說的啦  

、  風格和主題、  

風格主要是指view的顯示風格 res/values/filename.xml  

<?xml version=”1.0″ encoding=”utf-8″?> 

   <style name=”SpecialText” parent=”@style/Text”> 

   <item name=”android:textSize”>18sp</item> 

   <item name=”android:textColor”>#008</item> 

</style> 

主題主要針對Activity等, 可以在Android Manifest中定義的<application>和<activity>元素将主題添加到整個程式或者某個 Activity,但是主題是不能應用在某一個單獨的View裡.風格可以自己定義也可以使用程式自帶的或是繼承已有的風格。  

<?xml version="1.0" encoding="utf-8"?><resources><style name="CustomTheme"><item name="android:windowNoTitle">true</item><item name="windowFrame">@drawable/screen_frame</item><item name="windowBackground">@drawable/screen_background_white</item><item name="panelForegroundColor">#FF000000</item><item name="panelBackgroundColor">#FFFFFFFF</item><item name="panelTextColor">?panelForegroundColor</item><item name="panelTextSize">14</item><item name="menuItemTextColor">?panelTextColor</item><item name="menuItemTextSize">?panelTextSize</item></style></resources>   

、              動畫  

動畫資源分為兩種,一是實作圖檔的translate、scale、rotate、alpha四種變化。還可以設定動畫的播放特性;另一種是幀動畫,逐幀播放設定的資源  

先說一下第一種  

Res/anim/filename.xml<set xmlns:android="http://schemas.android.com/apk/res/android">                                   <translate android:interpolator="@android:anim/accelerate_interpolator"                                         android:fromXDelta="0" android:toXDelta="200" android:fromYDelta="0"                                         android:toYDelta="180" android:duration="2000" />                    <scale android:interpolator="@android:anim/accelerate_interpolator"                                         android:fromXScale="1.0" android:toXScale="2.0" android:fromYScale="1.0"                                         android:toYScale="2.0" android:pivotX="150%" android:pivotY="150%"                                         android:duration="2000" />                    <alpha android:fromAlpha="1.0" android:toAlpha="1.0"                                         android:duration="@android:integer/config_mediumAnimTime" />                    <rotate ....各個屬性></rotate>                    <Interpolator >可以使用其子類和屬性定義動畫的運作方式,先快後慢,先慢後快等</Interpolator></set>  具體參數的用法,大家可以自己查資料  

下面是第二種資源  

<animation-list xmlns:android=”http://schemas.android.com/apk/res/android”  

android:oneshot=”true”> 

<item android:drawable=”@drawable/rocket_thrust1″ android:duration=”200″ /> 

<item android:drawable=”@drawable/rocket_thrust2″ android:duration=”200″ /> 

<item android:drawable=”@drawable/rocket_thrust3″ android:duration=”200″ /> 

</animation-list> 

<script src="/javascripts/tinymce/plugins/javaeye/langs/zh.js" type="text/javascript"></script> rif;">1. 相關檔案夾介紹     在Android項目檔案夾裡面,主要的資源檔案是放在res檔案夾裡面的。assets檔案夾是存放不進行編譯加工的原生檔案,即該檔案夾裡面的檔案不會像xml,java檔案被預編譯,可以存放一些圖檔,html,js, css等檔案。在後面會介紹如何讀取assets檔案夾的資源! 

代碼示例

/Chapter03_Resource/src/com/amaker/test/MainActivity.java

package com.amaker.test;  

import android.app.ListActivity;  

import android.content.Intent;  

import android.os.Bundle;  

import android.view.View;  

import android.widget.ArrayAdapter;  

import android.widget.ListView;  

import com.amaker.ch03.color.TestColorActivity;  

import com.amaker.ch03.dimen.TestDimensionActivity;  

import com.amaker.ch03.drawable.TestBitmapActivity;  

import com.amaker.ch03.layout.TestLayoutActivity;  

import com.amaker.ch03.menu.TestMenuActivity;  

import com.amaker.ch03.string.TestStringActivity;  

import com.amaker.ch03.xml.TestXmlActivity;  

public class MainActivity extends ListActivity {  

    @Override 

    public void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        // 菜單項數組  

        String[] items = {"Test Color","Test String","Test Dimension","Test XML","Test Bitmap","Test Menu","Test Layout"};  

        // 将菜單項數組設定為ListView的清單項展示  

        setListAdapter(new ArrayAdapter<String>(this,  

                android.R.layout.simple_list_item_1, items));  

        getListView().setTextFilterEnabled(true);  

    }  

    // 響應菜單項的單擊事件  

    protected void onListItemClick(ListView l, View v, int position, long id) {  

        Intent intent = null;  

        switch (position) {  

        case 0:  

            intent = new Intent(MainActivity.this,TestColorActivity.class);  

            startActivity(intent);  

            break;  

        case 1:  

            intent = new Intent(MainActivity.this,TestStringActivity.class);  

        case 2:  

            intent = new Intent(MainActivity.this,TestDimensionActivity.class);  

        case 3:  

            intent = new Intent(MainActivity.this,TestXmlActivity.class);  

        case 4:  

            intent = new Intent(MainActivity.this,TestBitmapActivity.class);  

        case 5:  

            intent = new Intent(MainActivity.this,TestMenuActivity.class);  

        case 6:  

            intent = new Intent(MainActivity.this,TestLayoutActivity.class);  

        }  

擷取顔色資源

/Chapter03_Resource/src/com/amaker/ch03/color/TestColorActivity.java

package com.amaker.ch03.color;  

import android.app.Activity;  

import com.amaker.test.R;  

public class TestColorActivity extends Activity {  

        setContentView(R.layout.test_color);  

        // 引用顔色資源,設定背景色為紅色  

        getWindow().setBackgroundDrawableResource(R.color.red_bg);  

/Chapter03_Resource/res/values/colors.xml

 <?xml version="1.0" encoding="utf-8"?>

<resources>

    <color name="red_bg">#f00</color>

    <color name="blue_text">#0000ff</color>

</resources>

尺寸資源資源

/Chapter03_Resource/src/com/amaker/ch03/dimen/TestDimensionActivity.java

package com.amaker.ch03.dimen;  

import android.content.res.Resources;  

import android.widget.Button;  

public class TestDimensionActivity extends Activity {  

    private Button myButton;  

    @Override  

       setContentView(R.layout.test_dimen);  

       myButton = (Button)findViewById(R.id.Button01);  

       Resources r = getResources();  

       float btn_h = r.getDimension(R.dimen.btn_height);  

       float btn_w = r.getDimension(R.dimen.btn_width);  

       myButton.setHeight((int)btn_h);  

       myButton.setWidth((int)btn_w);  

/Chapter03_Resource/res/values/dimens.xml

    <dimen name="text_width">150px</dimen> 

    <dimen name="text_height">100px</dimen> 

    <dimen name="btn_width">30mm</dimen> 

    <dimen name="btn_height">10mm</dimen> 

Bitmap資源

/Chapter03_Resource/src/com/amaker/ch03/drawable/TestBitmapActivity.java

package com.amaker.ch03.drawable;  

import android.graphics.drawable.Drawable;  

import android.widget.ImageView;  

public class TestBitmapActivity extends Activity {  

    private ImageView myImageView;  

       setContentView(R.layout.test_bitmap);  

       myImageView = (ImageView)findViewById(R.id.bitmapImageView02);  

       Drawable d = r.getDrawable(R.drawable.moto);  

       myImageView.setImageDrawable(d);  

/Chapter03_Resource/res/drawable

布局資源

/Chapter03_Resource/src/com/amaker/ch03/layout/TestLayoutActivity.java

package com.amaker.ch03.layout;  

import android.widget.EditText;  

import android.widget.TextView;  

public class TestLayoutActivity extends Activity {  

    private TextView myTextView;  

    private EditText myEditText;  

       setContentView(R.layout.test_layout);  

       myTextView = (TextView)findViewById(R.id.layoutTextView01);  

       myEditText = (EditText)findViewById(R.id.layoutEditText01);  

       myButton = (Button)findViewById(R.id.layoutButton01);  

/Chapter03_Resource/res/layout/test_layout.xml

<LinearLayout   

    xmlns:android="http://schemas.android.com/apk/res/android" 

    android:orientation="vertical"   

    android:layout_width="fill_parent" 

    android:layout_height="fill_parent"> 

    <!-- 以上四個屬性分别是:命名空間、 元件布局方向(這裡是垂直)、布局的寬(充滿螢幕)和高(充滿螢幕)--> 

    <!--  以下嵌套一個TableLayout --> 

    <TableLayout   

    android:layout_width="fill_parent"   

    android:layout_height="fill_parent"   

    android:stretchColumns="1"> 

        <TableRow> 

            <TextView   

            android:text="測試Layout:"   

            android:id="@+id/layoutTextView01"   

            android:layout_width="wrap_content"   

            android:layout_height="wrap_content" 

            android:textColor="@color/red_bg"/> 

            <!-- 以上五個屬性分别是:文本内容、引用元件的ID、該元件的寬(内容的寬)、該元件的高(内容的高)、檔案顔色 --> 

            <EditText   

            android:text=""   

            android:id="@+id/layoutEditText01"   

            android:layout_width="fill_parent"   

            android:layout_height="wrap_content"/> 

        </TableRow> 

        <TableRow android:gravity="right"> 

            <Button   

            android:text="Test"   

            android:id="@+id/layoutButton01"   

            /> 

    </TableLayout> 

</LinearLayout> 

菜單資源

/Chapter03_Resource/src/com/amaker/ch03/menu/TestMenuActivity.java

package com.amaker.ch03.menu;  

import android.app.AlertDialog;  

import android.content.DialogInterface;  

import android.view.Menu;  

import android.view.MenuInflater;  

import android.view.MenuItem;  

public class TestMenuActivity extends Activity {  

    private MenuInflater mi;  

   public void onCreate(Bundle savedInstanceState) {  

       setContentView(R.layout.test_menu);  

       mi = new MenuInflater(this);  

    /*  

     * 建立菜單  

     */ 

    public boolean onCreateOptionsMenu(Menu menu) {  

        mi.inflate(R.menu.file_menu, menu);  

        return true;  

    public boolean onOptionsItemSelected(MenuItem item) {  

        switch (item.getItemId()) {  

        case R.id.about:  

            aboutAlert("本執行個體示範的是如何使用XML菜單資源來定義菜單!");  

        case R.id.exit:  

            exitAlert("真的要退出嗎?");  

    // 顯示對話框  

    private void exitAlert(String msg){  

        AlertDialog.Builder builder = new AlertDialog.Builder(this);  

        builder.setMessage(msg)  

               .setCancelable(false)  

               .setPositiveButton("确定", new DialogInterface.OnClickListener() {  

                   public void onClick(DialogInterface dialog, int id) {  

                       finish();  

                   }  

               }).setNegativeButton("取消", new DialogInterface.OnClickListener() {  

                       return;  

               });  

        AlertDialog alert = builder.create();  

        alert.show();  

    private void aboutAlert(String msg){  

/Chapter03_Resource/res/layout/test_menu.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    <TextView   

        android:text="測試菜單資源"   

        android:id="@+id/menuTextView01"   

        android:layout_width="wrap_content"   

        android:layout_height="wrap_content"></TextView> 

字元串資源

/Chapter03_Resource/src/com/amaker/ch03/string/TestStringActivity.java

package com.amaker.ch03.string;  

public class TestStringActivity extends Activity {  

       setContentView(R.layout.test_string);  

       myTextView = (TextView)findViewById(R.id.myTextView02);  

       String str = getString(R.string.test_str2).toString();  

       myTextView.setText(str);  

/Chapter03_Resource/res/layout/test_string.xml

    android:orientation="vertical" android:layout_width="fill_parent" 

        android:text="@string/test_str1"   

        android:id="@+id/myTextView01"   

        android:layout_height="wrap_content" 

        /> 

    android:text=""   

    android:id="@+id/myTextView02"   

    android:layout_width="wrap_content"   

    android:layout_height="wrap_content" 

    /> 

xml資源

package com.amaker.ch03.xml;  

import java.io.IOException;  

import org.xmlpull.v1.XmlPullParser;  

import org.xmlpull.v1.XmlPullParserException;  

import android.content.res.XmlResourceParser;  

import android.view.View.OnClickListener;  

public class TestXmlActivity extends Activity {  

       setContentView(R.layout.test_xml);  

       myTextView = (TextView)findViewById(R.id.xmlContentTextView01);  

       myButton = (Button)findViewById(R.id.xmltTestButton01);  

       myButton.setOnClickListener(new OnClickListener() {  

        @Override  

        public void onClick(View v) {  

               int counter = 0;  

               StringBuilder sb = new StringBuilder("");  

               Resources r = getResources();  

               XmlResourceParser xrp = r.getXml(R.xml.test);  

               try {  

                while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {   

                         if (xrp.getEventType() == XmlResourceParser.START_TAG) {   

                              String name = xrp.getName();  

                              if(name.equals("customer")){  

                                  counter++;  

                                  sb.append("第"+counter+"條客戶資訊:"+"\n");  

                                  sb.append(xrp.getAttributeValue(0)+"\n");  

                                  sb.append(xrp.getAttributeValue(1)+"\n");  

                                  sb.append(xrp.getAttributeValue(2)+"\n");  

                                  sb.append(xrp.getAttributeValue(3)+"\n\n");  

                              }  

                         } else if (xrp.getEventType() == XmlPullParser.END_TAG) {   

                         } else if (xrp.getEventType() == XmlPullParser.TEXT) {   

                         }   

                         xrp.next();   

                    }  

                myTextView.setText(sb.toString());  

            } catch (XmlPullParserException e) {  

                e.printStackTrace();  

            } catch (IOException e) {  

            }  

    });  

    <Button   

    android:text="獲得XML内容"   

    android:id="@+id/xmltTestButton01"   

    android:layout_height="wrap_content"></Button> 

    android:id="@+id/xmlContentTextView01"   

本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1080710