180

我想先从xml文件中读取字符串,然后再setText对小部件执行其他操作,那么如果没有要调用的活动对象,我该如何做到这一点getResources()

4

16 回答 16

393
  1. 创建 的子类Application,例如public class App extends Application {
  2. 将标签的android:name属性设置为指向您的新类,例如<application>AndroidManifest.xmlandroid:name=".App"
  3. onCreate()您的应用程序实例的方法中,将您的上下文(例如this)保存到一个名为的静态字段mContext并创建一个返回该字段的静态方法,例如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())。

于 2010-12-08T20:11:42.960 回答
104

仅用于系统资源!

利用

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

您可以在应用程序的任何地方使用它们,甚至在静态常量声明中!

于 2012-01-06T23:24:50.193 回答
23

我的 Kotlin 解决方案是使用静态应用程序上下文:

class App : Application() {
    companion object {
        lateinit var instance: App private set
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }
}

还有我到处使用的 Strings 类:

object Strings {
    fun get(@StringRes stringRes: Int, vararg formatArgs: Any = emptyArray()): String {
        return App.instance.getString(stringRes, *formatArgs)
    }
}

所以你可以有一个干净的方式来获取资源字符串

Strings.get(R.string.some_string)
Strings.get(R.string.some_string_with_arguments, "Some argument")

请不要删除这个答案,让我保留一个。

于 2019-10-30T14:36:23.937 回答
8

捷径

我使用App.getRes()而不是App.getContext().getResources()(正如@Cristian 回答的那样)

在代码中的任何地方使用都非常简单!

因此,这是一个独特的解决方案,您可以通过它从任何地方访问资源,例如Util class.

(1) 创建或编辑您的Application课程。

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 getRes() {
        return res;
    }

}

(2) 将名称字段添加到您的manifest.xml <application标签。(或如果已经存在则跳过此)

<application
        android:name=".App"
        ...
        >
        ...
    </application>

现在你可以走了。

App.getRes().getString(R.string.some_id)在代码中的任何地方使用。

于 2018-07-11T07:36:46.747 回答
7

还有另一种可能。我从以下资源加载 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)

于 2017-02-12T09:07:17.880 回答
3

单身人士:

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;
    }

}

在您的子类中初始化 Singleton Application

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 的钩子,用它调用它ApplicationContextSingleton.getInstance.getApplicationContext(); 你不应该在任何时候清除它,因为当应用程序关闭时,它无论如何都会随之而来。

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

<?xml version="1.0" encoding="utf-8"?>

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.domain.packagename"
    >

<application
    android:allowBackup="true"
    android:name=".mApplication" <!-- This is the important line -->
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:icon="@drawable/app_icon"
    >

现在您应该可以在任何地方使用 ApplicationContextSingleton.getInstance().getApplicationContext().getResources() 了,还有应用程序子类不能使用的极少数地方。

如果您在这里发现任何问题,请告诉我,谢谢。:)

于 2015-09-25T11:45:03.140 回答
2

另一种解决方案:

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

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,这很有用。

于 2016-10-21T23:58:24.547 回答
0

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

    import android.content.Context;

    import <your package>.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();
于 2014-08-13T19:23:04.623 回答
0

为什么你不尝试

Resources.getSystem().getString(R.string.foo);
于 2021-06-30T11:42:25.087 回答
0

我从静态函数加载 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() : "";
    }

    ...

}
于 2018-08-31T15:40:50.880 回答
0

我正在使用 API 级别 27,并在挣扎了大约两天后找到了最佳解决方案。如果要从不是从 Activity 或 Application 派生的类中读取 xml 文件,请执行以下操作。

  1. 将 testdata.xml 文件放在 assets 目录中。

  2. 编写以下代码,获取解析后的 testdata 文档。

        InputStream inputStream = this.getClass().getResourceAsStream("/assets/testdata.xml");
    
        // create a new DocumentBuilderFactory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // use the factory to create a documentbuilder
        DocumentBuilder builder = factory.newDocumentBuilder();
        // create a new document from input stream
        Document doc = builder.parse(inputStream);
    
于 2019-02-12T23:54:21.960 回答
0

这是您可以尝试的另一种略有不同的方法。

您可以Application像其他解决方案提到的那样子类化该类,并将静态引用存储到Resources.

创建一个应用程序类并在方法中初始化Resources变量。onCreate这将在您的应用启动时调用。我们可以WeakReference在这里使用来防止由于将此实例存储为静态变量而可能发生的内存泄漏(尽管这不太可能发生)

public class App extends Application {
    private static WeakReference<Resources> res;

由于您提到您只想从 xml 资源声明中检索字符串,因此无需将此资源变量公开给其他类,以封装资源实例并防止其泄漏。因此,您可以将引用存储为私有变量。

请记住在以下位置初始化此变量onCreate

@Override 
public void onCreate() { 
    super.onCreate(); 
    res = new WeakReference<>(getResources());
}

我们还需要在标签下声明应用程序android:name.App名称(或您设置的任何其他名称) 。AndroidManifest.xmlapplication

<application android:name=".App"
........... other attributes here ...........

检索字符串资源的另一种方法不是使用Resources其他类(或Context实例)中的实例,而是让App类在静态方法中为您获取它。这使实例保持封装/私有。

您可以在App类中使用静态方法来检索这些值(例如getStringGlobal,不要调用它getString,因为它会与默认方法冲突)

public static String getStringGlobal(@StringRes int resId) { 
   if (res != null && res.get() != null) { 
        return res.get().getString(resId); 
   } else {
        // This should not happen, you should throw an exception here, or you can return a fallback string to ensure the app still runs
    }
}

如所见,您还可以添加错误处理以防实例Resources不可用(这不应该发生,但以防万一)。

然后,您可以通过调用检索字符串资源

App.getStringGlobal(R.string./*your string resource name*/)

所以你的App.java

public class App extends Application { 
    private static WeakReference<Resources> res;

    @Override 
    public void onCreate() { 
        super.onCreate(); 
        res = new WeakReference<>(getResources());    
    }

    public static String getStringGlobal(@StringRes int resId) { 
       if (res != null && res.get() != null) { 
            return res.get().getString(resId); 
       } else {
        // This should not happen(reference to Resources invalid), you should throw an exception here, or you can return a fallback string to ensure the app still runs
       }
    }
}
于 2021-12-05T11:47:00.907 回答
0

在没有上下文的情况下将图像重新用作 InputStream:

Class<? extends MyClass> aClass = MyClass.class;
URL r = aClass.getResource("/res/raw/test.png");
URLConnection urlConnection = r.openConnection();
return new BufferedInputStream(urlConnection.getInputStream());

如果您的文件需要目录树,它也可以工作(资产支持子目录):

URL r = aClass.getResource("/assets/images/base/2.png");
于 2020-09-12T23:31:06.040 回答
-1

在您实现静态函数的类中,您可以从此类调用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');
于 2015-04-13T08:55:48.980 回答
-1

如果你有上下文,我的意思是在里面;

public void onReceive(Context context, Intent intent){

}

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

context.getResources().getString(R.string.app_name);
于 2015-05-26T12:51:41.833 回答
-1
public Static Resources mResources;

 @Override
     public void onCreate()
     {
           mResources = getResources();
     }
于 2018-09-26T07:21:18.573 回答