Cannot resolve maketext() method of Toast

后端 未结 18 2410
旧时难觅i
旧时难觅i 2021-02-07 02:02

I am getting error while creating a Toast

Toast toast = Toast.makeText(this, text, duration);

I am getting cannot resolve ma

相关标签:
18条回答
  • 2021-02-07 02:37

    In the onClick(View view) click listener within a RecyclerView.ViewHolder the context is retrieved with view.getContext(), as in:

    ```

    public class MyHolder extends RecyclerView.ViewHolder implements 
    View.OnClickListener {
    
        public MyHolder(View itemView) {
            super(itemView);
            //...
            itemView.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(), "the message", 
                Toast.LENGTH_SHORT).show();
        }
    

    ```

    0 讨论(0)
  • 2021-02-07 02:37

    Grab the context from the calling activity (eg. this or MainActivity.this) and pass it into the method your Toast resides in. That way it lives together with the calling activity.

    Application context, which you get from getApplicationContext() and getContext() is mainly for long running processes. Using it for short lived processes can lead to memory leaks.

    0 讨论(0)
  • 2021-02-07 02:39

    this in your case might not be the object of the activity. You might be using the Toast.makeText method inside you Click Listener object. To resolve this you need to use getApplicationContext() :

    Toast.makeText(getApplicationContext() , "Your Message", Toast.LENGTH_LONG);

    0 讨论(0)
  • 2021-02-07 02:39

    This might be helpful if you are trying to use Toast in Fragment:

    Toast.makeText(Your_Fragment_Name.super.getContext(), "Added", Toast.LENGTH_SHORT).show();
    
    0 讨论(0)
  • 2021-02-07 02:40

    Instead of

    Toast toast = Toast.makeText(this, text, duration);  
    

    Add your activity name before "this" word

    Toast toast = Toast.makeText(MyActivity.this, text, duration); 
    
    0 讨论(0)
  • 2021-02-07 02:41

    in the onClick method try this

    
    Toast.makeText(view.getContext(), "sorry", Toast.LENGTH_LONG).show();
    
    
    

    it did work form me.

    0 讨论(0)
提交回复
热议问题