展会信息港展会大全

Android ApiDemos示例解析(48):Content->Resources->Resources
来源:互联网   发布日期:2016-01-14 11:13:58   浏览:1313次  

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

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开发 教程

AiLab云推荐
推荐内容
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港