using a string resource in a Toast

淺唱寂寞╮ 提交于 2019-11-29 13:21:48

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

Change to

 public static void ToastMemoryShort (Context context) {

        Toast.makeText(context, context.getString(R.string.toast_memoryshort), Toast.LENGTH_LONG).show();
        return;
        }
Víctor García

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

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)

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.

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