Android數據訪問(二)——Resource

### 使用Resource訪問程序數據## ———-   Resource一般用來取得res目錄內的資源。要取得res目錄內的資源,基本都是通過資源的resource ID來取得,即通過R文件。這種方法,可以取得很多類型的文件,如文本文件,圖像,影音,還有UI組件。我們剛開始寫Android程序時,用findViewById()方法來獲取控件,就是這種方法的典型應用。下面的例子中,通過這種方法來獲取文本,圖片和音頻。   這裏只寫主要代碼,其他由編譯器自動生成的代碼就不寫了。 activity_main.xml文件
//這裏寫了3個TextView和一個ImageView,用來顯示取得的文字和圖像
    <TextView
        android:id="@+id/strText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/txtText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/strText"
        android:layout_below="@+id/strText"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/recText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/txtText"
        android:layout_below="@+id/txtText"
        android:text="@string/hello_world" />

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/recText"
        android:layout_alignLeft="@+id/strText"
         />
在strings.xml中添加一行代碼 “` 永別了武器 海明威 “` 這個字符串是帶格式的,“`永別了武器 “`表示的是文字帶有下劃線。 然後是MainActivity.java文件:
public class MainActivity extends Activity {

    TextView strText = null;
    TextView txtText = null;
    TextView recText = null;
    ImageView img = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();

    }
    public void findViews(){
        strText = (TextView)findViewById(R.id.strText);
        txtText = (TextView)findViewById(R.id.txtText);
        recText = (TextView)findViewById(R.id.recText);
        img = (ImageView)findViewById(R.id.img);

        Resources res = this.getResources();//獲取Resource對象
        //注意下面三種獲取字符串的方法
        CharSequence text1 = getString(R.string.info);  //獲取的文本不保留格式,只保留純文字
        CharSequence text2 = getText(R.string.info);    //獲取的文本保留了格式
        CharSequence text3 = getText(R.string.info);    //仍然獲取有格式的字符串,這裏要特別注意一下,待會兒看下面的代碼

        strText.setText(text1);//第一個TextView中設置沒有格式的字符串
        txtText.setText(text2);//第二個TextView中設置有格式的字符串
        recText.setText("Resources:"+text3);
        //第三個textView中,將有格式的字符串text3和一個普通字符串"Resources:"相加一下,可以看到下面的程序運行結果,發現"永別了,武器"這一行字的下劃線沒有了,這說明一個有格式的字符串和一個普通無符號字符串相加,會進行強制類型轉換,結果是一個無符號的字符串
        img.setImageDrawable(res.getDrawable(R.drawable.beautiful_love_wallpapers_for_twitter));//獲取drawable文件夾下的一張圖
        MediaPlayer mp = MediaPlayer.create(MainActivity.this,R.raw.when_we_were_young);//獲取raw文件夾下的一個音頻文件,程序運行時會自動播放歌曲
        mp.start();//開始播放
    }
}

運行結果

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