java获取上下文根_java - 如何从静态上下文中获取资源内容?

在没有活动对象可以使用getResources()的情况下,可以通过创建一个App的子类并保存上下文到静态字段,然后提供一个静态方法来获取这个上下文。例如,创建一个名为App的类,继承自Application,并在onCreate()方法中保存上下文。之后,可以通过App.getContext().getResources()来获取资源。此外,还可以使用Resources.getSystem().getString(android.R.string.cancel)来获取系统资源,但仅限于系统资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java - 如何从静态上下文中获取资源内容?

我想要在小部件上执行setText之类的其他操作之前读取xml文件中的字符串,那么如果没有活动对象可以打开getResources(),我怎么能这样做呢?

11个解决方案

339 votes

创建一个App.getContext()的子类,例如App.getContext()

将getResources()中getResources()标记的App.getContext()属性设置为指向新类,例如getContext()

在您的应用实例的App.getContext()方法中,将您的上下文(例如getResources())保存到名为App.getContext().getResources()的静态字段中,并创建一个返回此字段的静态方法,例如getContext():

它应该是这样的:

public class App extends Application{

private static Context mContext;

@Override

public void onCreate() {

super.onCreate();

mContext = this;

}

public static Context getContext(){

return mContext;

}

}

现在你可以使用:App.getContext()每当你想获得一个上下文,然后getResources()(或App.getContext().getResources())。

Cristian answered 2019-05-06T14:51:53Z

96 votes

使用

Resources.getSystem().getString(android.R.string.cancel)

您可以在应用程序的任何地方使用它们,即使在静态常量声明中也是如此!但仅限系统资源!

Gangnus answered 2019-05-06T14:52:25Z

3 votes

单身人士:

package com.domain.packagename;

import android.content.Context;

/**

* Created by Versa on 10.09.15.

*/

public class ApplicationContextSingleton {

private static PrefsContextSingleton mInstance;

private Context context;

public static ApplicationContextSingleton getInstance() {

if (mInstance == null) mInstance = getSync();

return mInstance;

}

private static synchronized ApplicationContextSingleton getSync() {

if (mInstance == null) mInstance = new PrefsContextSingleton();

return mInstance;

}

public void initialize(Context context) {

this.context = context;

}

public Context getApplicationContext() {

return context;

}

}

在AndroidManifest.xml子类中初始化Singleton:

package com.domain.packagename;

import android.app.Application;

/**

* Created by Versa on 25.08.15.

*/

public class mApplication extends Application {

@Override

public void onCreate() {

super.onCreate();

ApplicationContextSingleton.getInstance().initialize(this);

}

}

如果我没错,这会给你一个applicationContext到处的钩子,用AndroidManifest.xml调用它你不应该在任何时候都清楚这一点,因为当应用程序关闭时,无论如何都是这样。

记得更新AndroidManifest.xml以使用此Application子类:

xmlns:android="http://schemas.android.com/apk/res/android"

package="com.domain.packagename"

>

android:allowBackup="true"

android:name=".mApplication"

android:label="@string/app_name"

android:theme="@style/AppTheme"

android:icon="@drawable/app_icon"

>

现在你应该能够从任何地方使用ApplicationContextSingleton.getInstance()。getApplicationContext()。getResources(),也就是应用程序子类不能使用的极少数地方。

如果你在这里看到任何错误,请告诉我,谢谢。:)

Versa answered 2019-05-06T14:53:22Z

3 votes

还有另一种可能性。 我从这样的资源加载OpenGl着色器:

static private String vertexShaderCode;

static private String fragmentShaderCode;

static {

vertexShaderCode = readResourceAsString("/res/raw/vertex_shader.glsl");

fragmentShaderCode = readResourceAsString("/res/raw/fragment_shader.glsl");

}

private static String readResourceAsString(String path) {

Exception innerException;

Class extends FloorPlanRenderer> aClass = FloorPlanRenderer.class;

InputStream inputStream = aClass.getResourceAsStream(path);

byte[] bytes;

try {

bytes = new byte[inputStream.available()];

inputStream.read(bytes);

return new String(bytes);

} catch (IOException e) {

e.printStackTrace();

innerException = e;

}

throw new RuntimeException("Cannot load shader code from resources.", innerException);

}

如您所见,您可以访问路径/res/...中的任何资源改变aClass到你的班级。 这也是我如何在测试中加载资源(androidTests)

Gregory Stein answered 2019-05-06T14:54:02Z

1 votes

另一种方案:

如果在非静态外部类中有静态子类,则可以通过外部类中的静态变量从子类中访问资源,该外部类在创建外部类时初始化。 喜欢

public class Outerclass {

static String resource1

public onCreate() {

resource1 = getString(R.string.text);

}

public static class Innerclass {

public StringGetter (int num) {

return resource1;

}

}

}

我将它用于我的FragmentActivity中的静态FragmentPagerAdapter的getPageTitle(int position)函数,因为I8N很有用。

Stephan Brunker answered 2019-05-06T14:54:45Z

0 votes

我想,更多的方法是可能的。但有时,我使用这个解决方案。 (全球):

import android.content.Context;

import .R;

public class XmlVar {

private XmlVar() {

}

private static String _write_success;

public static String write_success() {

return _write_success;

}

public static void Init(Context c) {

_write_success = c.getResources().getString(R.string.write_success);

}

}

//After activity created:

cont = this.getApplicationContext();

XmlVar.Init(cont);

//And use everywhere

XmlVar.write_success();

user2684935 answered 2019-05-06T14:55:15Z

0 votes

在您的类中,您实现静态函数,您可以从此类调用private \ public方法。 private \ public方法可以访问getResources。

例如:

public class Text {

public static void setColor(EditText et) {

et.resetColor(); // it works

// ERROR

et.setTextColor(getResources().getColor(R.color.Black)); // ERROR

}

// set the color to be black when reset

private void resetColor() {

setTextColor(getResources().getColor(R.color.Black));

}

}

从其他类\活动中,您可以致电:

Text.setColor('some EditText you initialized');

Erez Shmiel answered 2019-05-06T14:55:55Z

0 votes

如果你有一个背景,我的意思是在里面;

public void onReceive(Context context, Intent intent){

}

您可以使用此代码获取资源:

context.getResources().getString(R.string.app_name);

eren130 answered 2019-05-06T14:56:30Z

0 votes

我喜欢快捷方式。

我使用App.getRes().getString(R.string.some_id)而不是

什么? 在您的应用中的任何地方使用都非常简单!

因此,这是一个独特的解决方案,您可以通过它从App.getRes().getString(R.string.some_id)等任何地方访问资源。

(1)创建或编辑您的App.getRes().getString(R.string.some_id)课程。

import android.app.Application;

import android.content.res.Resources;

public class App extends Application {

private static App mInstance;

private static Resources res;

@Override

public void onCreate() {

super.onCreate();

mInstance = this;

res = getResources();

}

public static App getInstance() {

return mInstance;

}

public static Resources getResourses() {

return res;

}

}

(2)将名称字段添加到App.getRes().getString(R.string.some_id)

android:name=".App"

...

>

...

现在你很高兴。 在应用程序的任何地方使用App.getRes().getString(R.string.some_id)。

Khemraj answered 2019-05-06T14:57:42Z

0 votes

我从静态函数加载了用于openGL ES的着色器。

请记住,您必须使用小写字母作为文件和目录名称,否则操作将失败

public class MyGLRenderer implements GLSurfaceView.Renderer {

...

public static int loadShader() {

// Read file as input stream

InputStream inputStream = MyGLRenderer.class.getResourceAsStream("/res/raw/vertex_shader.txt");

// Convert input stream to string

Scanner s = new Scanner(inputStream).useDelimiter("\\A");

String shaderCode = s.hasNext() ? s.next() : "";

}

...

}

user2174870 answered 2019-05-06T14:58:17Z

0 votes

public Static Resources mResources;

@Override

public void onCreate()

{

mResources = getResources();

}

Makvin answered 2019-05-06T14:58:39Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值