using a string resource in a Toast

我们两清 提交于 2019-12-29 08:30:10

问题


My code is:

public static void ToastMemoryShort (Context context) {
    CharSequence text = getString(R.string.toast_memoryshort); //error here
    Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    return;
    }

but I'm getting "Cannot make a static reference to the non-static method getString(int) from the type Context" in Eclipse. I'm trying to get ready for localising my app (getting all the hard coded strings into resources), so where I have:

getString(R.string.toast_memoryshort)

I previously had a hard coded string which was fine.

I'm not sure what's going on here (Java noob). Can anyone enlighten me please?

Many thanks

Baz


回答1:


Just use this instead:

makeText(Context context, int resId, int duration) Make a standard toast that just contains a text view with the text from a resource.

From http://developer.android.com/reference/android/widget/Toast.html




回答2:


Change to

 public static void ToastMemoryShort (Context context) {

        Toast.makeText(context, context.getString(R.string.toast_memoryshort), Toast.LENGTH_LONG).show();
        return;
        }



回答3:


You could make your toast more generic like this:

public void toast(String msg){
    Context context = getApplicationContext();
    CharSequence text = msg;
    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}

Then just call when you need like this:

toast( "My message hardcoded" );

or by referring to strings.xml like this:

toast( this.getString(R.string.toast_memoryshort) );



回答4:


You should change

CharSequence text = getString(R.string.toast_memoryshort); //error here

for:

CharSequence text = context.getString(R.string.toast_memoryshort);

The getString function is implemented in Context#getString(int)




回答5:


Use the below code to get the desired output:

Toast.makeText(getApplicationContext(),getString(R.string.exit_survey_toast),Toast.LENGTH_LONG).show();

replace exit_survey_toast with your string value.



来源:https://stackoverflow.com/questions/7331793/using-a-string-resource-in-a-toast

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