您的位置:首页 > 移动开发 > Android开发

Android数据访问(二)——Resource

2015-03-30 22:52 218 查看
### 使用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();//开始播放
}
}




运行结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android