Toast inside a Button OnclickListener is not worki

2019-03-07 03:30发布

intdelay was initialized at the beginning of the code by 1000. and I am trying to make sure that intdelay's value is updated by the value in the edit box by adding a toast when the button is clicked. but when I run the app, I get the following problem:

 Error:(46, 22) error: no suitable method found for makeText(<anonymous OnClickListener>,String,int)
method Toast.makeText(Context,CharSequence,int) is not applicable
(argument mismatch; <anonymous OnClickListener> cannot be converted to Context)
method Toast.makeText(Context,int,int) is not applicable
(argument mismatch; <anonymous OnClickListener> cannot be converted to Context)

This is the part of my code:

  @Override
        protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        delayedttxt=(EditText)findViewById(R.id.delayedttxt);

    String delay=delayedttxt.getText().toString();       //this will get a string
    try{
        int intdelay = Integer.parseInt(delay);
   }catch(NumberFormatException ex){ // handle your exception
    }

    Button btn=(Button)findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            flashLight.switchFlash();
            Toast.makeText(this,"your integer is " + intdelay , Toast.LENGTH_LONG).show();
        }

    });

How can I solve that?

8条回答
萌系小妹纸
2楼-- · 2019-03-07 03:35

Try like this:

Toast.makeText(YourActivityName.this,"your integer is " + intdelay , Toast.LENGTH_LONG).show();
查看更多
Deceive 欺骗
3楼-- · 2019-03-07 03:40

You are trying to show your toast inside the OnClickListener. The this keyword in this case refers to an instance of type OnClickListener, and not Context, like it is required.

You should use <YourActivityClass>.this to refer to the enclosing activity instance, that is a Context and can be use to show the toast.

查看更多
家丑人穷心不美
4楼-- · 2019-03-07 03:40

You should change from

Toast.makeText(this,"your integer is " + intdelay , Toast.LENGTH_LONG).show();

to

Toast.makeText(getContext(),"your integer is " + intdelay , Toast.LENGTH_LONG).show();
查看更多
ゆ 、 Hurt°
5楼-- · 2019-03-07 03:42

That's because makeText wants to have a Context as a first argument. You are inside the onClick function of an OnClickListener. This means that this points to your OnClickListener.
You must have something like this

Toast.makeText(YourActivity.this,"your integer is " + intdelay , Toast.LENGTH_LONG).show();
查看更多
混吃等死
6楼-- · 2019-03-07 03:46

Try inserting this line of code:

 Toast.makeText(getApplicationContext(),"your integer is " + intdelay , Toast.LENGTH_LONG).show();
查看更多
走好不送
7楼-- · 2019-03-07 03:47

Please do these in your activity,

Toast.makeText(getApplicationContext(),"your integer is " + intdelay , Toast.LENGTH_LONG).show();
查看更多
登录 后发表回答