Android, using Toast inside onClickListener

老子叫甜甜 提交于 2019-12-01 19:26:14

问题


I am trying to make a toast display some text given certain conditions inside an onClickListener. The app won´t run in the simulator, and I get the following error: "void cannot be converted to Toast"

I have searched around, and find several similar problems and solutions on this forum, but none of them applies completely to my problem. The others haven´t used the correct context in the statement, but I really mean that I do. (The name of the javafile (context) is: "Case1Activity") Can anyone help me with this? I have simplified the code a bit:

public void onClick(View view) {
            if (button1Pushed == false){
                count++;
                Toast toast = Toast.makeText(Case1Activity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();
            }


        }
    });

回答1:


do it without assignment statement

Toast.makeText(Case1Activity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();



回答2:


apply it as.

Toast.makeText(Case1Activity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();



回答3:


if you want to use assignment operator then you can use below code

Toast toast = Toast.makeText(context, text, duration);
toast.show();



回答4:


Dear Friend check below before eating Toast,

Your Toast (Incompatible types error) :

 Toast toast = Toast.makeText(Case1Activity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show(); 

Normal Case (Standard Use):

Toast.makeText(Case1Activity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();`

Special Case (if you need reference of Toast):

 View toast = Toast.makeText(MainActivity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();

because here ".show()" method is -

public void show () which shows the view for the specified duration.

Thanks



来源:https://stackoverflow.com/questions/40437997/android-using-toast-inside-onclicklistener

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