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
 

發佈留言