using a string resource in a Toast

前端 未结 5 1579
不知归路
不知归路 2020-12-18 23:25

My code is:

public static void ToastMemoryShort (Context context) {
    CharSequence text = getString(R.string.toast_memoryshort); //error here
    Toast.mak         


        
相关标签:
5条回答
  • 2020-12-18 23:51

    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) );
    
    0 讨论(0)
  • 2020-12-18 23:53

    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.

    0 讨论(0)
  • 2020-12-18 23:56

    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 讨论(0)
  • 2020-12-19 00:05

    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

    0 讨论(0)
  • 2020-12-19 00:06

    Change to

     public static void ToastMemoryShort (Context context) {
    
            Toast.makeText(context, context.getString(R.string.toast_memoryshort), Toast.LENGTH_LONG).show();
            return;
            }
    
    0 讨论(0)
提交回复
热议问题