-2

When I type code like this in MainActivity:-

Button btn=(Button) findViewById(R.id.mainButton1);
btn.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View p1)
    {
        Toast.makeText(this,"Some text...",Toast.LENGTH_SHORT).show();
    }
});

It shows the error

There is no applicable method to '(com.example.MainActivity.(anonymous),java.lang.String,int)'

but

Button btn=(Button) findViewById(R.id.mainButton1);
btn.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View p1)
    {
        Toast.makeText(MainActivity.this,"Some text...",Toast.LENGTH_SHORT).show();
    }
});

This not shows the error, So is any difference present in MainActivity.this and this

please vote to delete this post because nothing is useful in this post for future readers. All information is given in duplicate question

Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30

1 Answers1

4

When you are doing this :

Button btn=(Button) findViewById(R.id.mainButton1);
btn.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View p1)
    {
        Toast.makeText(MainActivity.this,"Some text...",Toast.LENGTH_SHORT).show();
    }
 });

you are creating an anonymous class with the implementation of interface OnClickListener.

Now, when you use this keywork inside onClick(), the this here refers to the instance of the anonymous class created (although you also have access to the instance of MainActivity), therefore, to refer to the instance of MainActivity, you have to use MainActivity.this.

Shrey Garg
  • 1,317
  • 1
  • 7
  • 17