getResources 不起作用/未定义的 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4338400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:07:29  来源:igfitidea点击:

getResources does not work / undefined Java

javaandroidundefined

提问by Udo

I have a problem with caling the getResources()function in an standard class. All imports must be there to use the function. Is there any special class I need to extend my class?

getResources()在标准类中调用函数时遇到问题。所有导入都必须在那里才能使用该功能。我需要扩展我的课程有什么特殊的课程吗?

Thanks for the immediate help.

感谢您的即时帮助。

package com.example.helloandroid;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;

import android.content.res.Resources;

import android.content.Intent;
import android.os.Bundle;

//import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DbAdapter {

    public DbAdapter() {
     Resources res = getResources();//error: The method getResources() is undefined for the type DbAdapter
            //also tyed context.getResources()
    }


}

采纳答案by ccheneson

getResoucesis a method of a Context. So you can pass the context to your DbAdapter constructor and call getResourcesfrom it :

getResouces是一个Context的方法。因此,您可以将上下文传递给 DbAdapter 构造函数并getResources从中调用:

public DbAdapter(Context context) {
     Resources res = context.getResources();//error: The method getResources() is undefined for the type DbAdapter
            //also tied context.getResources()
}

回答by Ujwal Tale

Define Context'sobject and then call all the R.<Methods>with the help of contextobject .

定义Context'sobject 然后R.<Methods>contextobject的帮助下调用所有的。

Eg:

例如:

Context ctx;
ctx.getResources().getString(R.string.Forgot_message);

Above code is working for me .

上面的代码对我有用。

回答by Patapoom

If your Adapter is for example an ArrayAdapter, you can use this:

例如,如果您的适配器是一个 ArrayAdapter,您可以使用它:

getContext().getResources();

getContext().getResources();