Programing

정적 컨텍스트에서 리소스 컨텐츠를 얻으려면 어떻게해야합니까?

lottogame 2020. 6. 4. 07:52
반응형

정적 컨텍스트에서 리소스 컨텐츠를 얻으려면 어떻게해야합니까?


위젯 xml과 같은 다른 많은 작업을 수행하기 전에 파일 에서 문자열을 읽고 싶습니다 setText. 따라서 활동 객체를 호출하지 않고 어떻게 할 수 getResources()있습니까?


  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())를 사용할 수 있습니다.


사용하다

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

정적 상수 선언에서도 응용 프로그램의 모든 곳에서 사용할 수 있습니다! 그러나 시스템 리소스에만 해당됩니다!


싱글 톤 :

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

}

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

내가 틀리지 않으면 응용 프로그램 컨텍스트에 대한 후크를 제공합니다. 호출하십시오. ApplicationContextSingleton.getInstance.getApplicationContext();응용 프로그램을 닫을 때 언제든지 지울 필요가 없습니다.

AndroidManifest.xmlApplication서브 클래스 를 사용 하도록 업데이트하십시오 :

<?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 ()를 사용할 수 있어야하며 응용 프로그램 서브 클래스가없는 곳도 거의 없습니다.

여기에 잘못된 것이 있으면 알려주십시오. 감사합니다. :)


또 다른 가능성이 있습니다. 다음과 같은 리소스에서 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);
}

As you can see, you can access any resource in path /res/... Change aClass to your class. This also how I load resources in tests (androidTests)


Another solution:

If you have a static subclass in a non-static outer class, you can access the resources from within the subclass via static variables in the outer class, which you initialise on creation of the outer class. Like

public class Outerclass {

    static String resource1

    public onCreate() {
        resource1 = getString(R.string.text);
    }

    public static class Innerclass {

        public StringGetter (int num) {
            return resource1; 
        }
    }
}

I used it for the getPageTitle(int position) Function of the static FragmentPagerAdapter within my FragmentActivity which is useful because of I8N.


Shortcut

I use App.getRes() instead of App.getContext().getResources() (as @Cristian answered)

It is very simple to use anywhere in your code!

So here is a unique solution by which you can access resources from anywhere like Util class .

(1) Create or Edit your Application class.

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) Add name field to your manifest.xml <application tag. (or Skip this if already there)

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

Now you are good to go.

Use App.getRes().getString(R.string.some_id) anywhere in code.


I think, more way is possible. But sometimes, I using this solution. (full global):

    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();

In your class, where you implement the static function, you can call a private\public method from this class. The private\public method can access the getResources.

for example:

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

and from other class\activity, you can call:

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

I load shader for openGL ES from static function.

Remember you must use lower case for your file and directory name, or else the operation will be failed

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() : "";
    }

    ...

}

public Static Resources mResources;

 @Override
     public void onCreate()
     {
           mResources = getResources();
     }

I am using API level 27 and found a best solution after struggling for around two days. If you want to read a xml file from a class which doesn't derive from Activity or Application then do the following.

  1. Put the testdata.xml file inside the assets directory.

  2. Write the following code to get the testdata document parsed.

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

if you have a context, i mean inside;

public void onReceive(Context context, Intent intent){

}

you can use this code to get resources:

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

참고URL : https://stackoverflow.com/questions/4391720/how-can-i-get-a-resource-content-from-a-static-context

반응형