如何在Android中使用资源

发布于 2024-10-02 19:02:55 字数 249 浏览 0 评论 0原文

一个人如何使用资产?我有这段代码:

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

它似乎只能在 Activity 类中使​​用。如果我尝试在另一个类中使用上述代码,我会收到有关 getAssets() 不是我的类的类型的错误。

那么如何在不是 Activity 的类中使用资源呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请恋爱 2024-10-09 19:02:55

您必须传递要使用活动上下文的类。为了在您的活动中获得正确的上下文,您可以执行以下操作。

private Context ctx = null;

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

    MyClass myClass = new MyClass(ctx);
}

其中 MyClass 是您正在谈论的课程。在您的类中,您必须在类构造函数中处理上下文。

class MyClass {
    Context ctx = null;

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

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;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文