如何使用资产的Andr​​oid [英] How to use assets in Android

查看:127
本文介绍了如何使用资产的Andr​​oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何做一资产使用?我有这个code:

How do one use assets? I have this code:

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

据接缝喜欢它只能通过在Activity类使用。如果我尝试使用上面的code另一类我得到getAssets()的错误不是我的类的类型。

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?

推荐答案

您必须通过要使用您的活动的背景下类。为了得到正确的上下文中,你的活动,你做这样的事情。

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

在哪里MyClass的是你正在谈论的类。在你的类,你必须处理的背景下在类的构造函数。

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

这篇关于如何使用资产的Andr​​oid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆