using a string resource in a Toast

2019-01-27 21:19发布

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

4条回答
仙女界的扛把子
2楼-- · 2019-01-27 21:35

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

查看更多
▲ chillily
3楼-- · 2019-01-27 21:37

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)

查看更多
爷、活的狠高调
4楼-- · 2019-01-27 21:43

Change to

 public static void ToastMemoryShort (Context context) {

        Toast.makeText(context, context.getString(R.string.toast_memoryshort), Toast.LENGTH_LONG).show();
        return;
        }
查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-27 21:54

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) );
查看更多
登录 后发表回答