How to use assets in Android

☆樱花仙子☆ 提交于 2019-12-24 00:43:29

问题


How do one use assets? I have this code:

AssetManager assets = getAssets();
InputStream stream = assets.open( "test.txt" );

It seams like it can only by used in an Activity class. If I try to use the above code in another class I get an error about getAssets() is not a type for my class.

So how do one use assets in a class that is not an Activity?


回答1:


You have to pass that class you want to use your activity's context. To get the correct context in you activity you do something like this.

private Context ctx = null;

public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    // your other code
    ctx = getApplication();

    MyClass myClass = new MyClass(ctx);
}

Where MyClass is the class you are talking about. In your class you have to handle the context to in your classes constructor.

class MyClass {
    Context ctx = null;

    public MyClass(Context ctx) {
        this.ctx = ctx;
    }
}


来源:https://stackoverflow.com/questions/4162623/how-to-use-assets-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!