开发者

using a string resource in a Toast

My co开发者_开发知识库de 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


Change to

 public static void ToastMemoryShort (Context context) {

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


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


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


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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜