当前位置:操作系统 > 安卓/Android >>

Android ApiDemos示例解析(48):Content->Resources->Resources

Android SDK对应没个定义在res目录下的资源都会定义一个维一的资源ID。在编译时会在gen目录下生成 R.java , 资源ID的格式为 R.[type].[id] 类型为资源类型如anim, array, attr等

 

\

可以在代码或是XML资源文件(如layout, style中)访问这些资源。

Context类提供了访问资源的方法,一是直接通过如getText, getString等来访问资源,此外一般的方法是通过getResources()来取代Resources对象,再通过Resources对象来访问资源。下图为Context的类继承图:

 

\

可以看到Application ,Service ,Activity 都是Context的子类,因此在这些类中都可以直接访问资源:

[java] 
// Using the getString() conevenience method,   
// retrieve a string   
// resource that hapepns to have style information.   
//Note the use of   
// CharSequence instead of String so we don't   
// lose the style info.   
cs = getText(R.string.styled_text);  
tv = (TextView)findViewById(R.id.styled_text);  
tv.setText(cs);  
   
// Use the same resource, but convert it to a   
//string, which causes it   
// to lose the style information.   
str = getString(R.string.styled_text);  
tv = (TextView)findViewById(R.id.plain_text);  
tv.setText(str);  
   
// You might need to do this if your code   
// is not in an activity.   
// For example View has a protected mContext   
//field you can use.   
// In this case it's just 'this' since   
//Activity is a context.   
Context context = this;  
   
// Get the Resources object from our context   
Resources res = context.getResources();  
   
// Get the string resource, like above.   
cs = res.getText(R.string.styled_text);  
tv = (TextView)findViewById(R.id.res1);  
tv.setText(cs); 
// Using the getString() conevenience method,
// retrieve a string
// resource that hapepns to have style information.
//Note the use of
// CharSequence instead of String so we don't
// lose the style info.
cs = getText(R.string.styled_text);
tv = (TextView)findViewById(R.id.styled_text);
tv.setText(cs);
 
// Use the same resource, but convert it to a
//string, which causes it
// to lose the style information.
str = getString(R.string.styled_text);
tv = (TextView)findViewById(R.id.plain_text);
tv.setText(str);
 
// You might need to do this if your code
// is not in an activity.
// For example View has a protected mContext
//field you can use.
// In this case it's just 'this' since
//Activity is a context.
Context context = this;
 
// Get the Resources object from our context
Resources res = context.getResources();
 
// Get the string resource, like above.
cs = res.getText(R.string.styled_text);
tv = (TextView)findViewById(R.id.res1);
tv.setText(cs);

 \

 作者:mapdigit
 

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,