Toast.makeText from resource string

前端 未结 4 1521
南旧
南旧 2020-12-29 17:00

I have a class named MyPrimaryClass, this class has a button witch when pressed, creates an Intent with the class myClassForResult.

I use this to start it:



        
相关标签:
4条回答
  • 2020-12-29 17:26

    @dilipkaklotar Answered correctly but a few changes needs to be done:

    this is how it worked for me

    Toast.makeText(getApplicationContext(),
    getApplicationContext().getResources().getString(R.string.message),
    Toast.LENGTH_SHORT).show();
    

    the getResources has no parenthesis (). and at the end is .show(); not toShow().

    but it's correct. so thank you very much.

    0 讨论(0)
  • 2020-12-29 17:27
    Toast.makeText(getApplicationContext(), getApplicationContext().getResources.getString(R.string.imgval), Toast.LENGTH_SHORT).toShow();
    
    0 讨论(0)
  • 2020-12-29 17:41

    One thing to note:

    Toast toast = Toast.makeText(c,
        c.getResources().getString(R.string.my_resource_string),
        Toast.LENGTH_SHORT);
    toast.show();
    

    Can be simplified into:

    Toast.makeText(c,
        c.getResources().getString(R.string.my_resource_string),
        Toast.LENGTH_SHORT).show();
    

    This saves you an object reference that you do not need.

    One thing you need to understand is that whenever you reference you R in your package (not android.R.) you will have access to your resources as long as you have Context.

    Update

    After realizing what you are using this for I would recommend that you change your approach, while this is in fact possible, your approach isn't ideal for something so simple.

    The method startActivityForResult(xx) is typically when you want to start an application that is outside of your package for a result.

    For instance: if I wanted to retrieve a barcode from a product, then I'd start an Intent to that barcode class, indirectly through an action. Then I'd retrieve the data through using onActivityResult(xx).

    it makes No Sense to do this for your own classes.

    0 讨论(0)
  • 2020-12-29 17:53

    Try:

    Toast.makeText(this, this.getString(R.string.my_resource_string), Toast.LENGTH_SHORT);
    
    0 讨论(0)
提交回复
热议问题