How to use assets in Android

2019-07-11 13:00发布

问题:

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