what is the activity name in anonymous class

[亡魂溺海] 提交于 2019-12-02 08:14:40

Inside anonymous class, this refers to the block of the anonymous class. To refer to the Activity class which contains the anonymous class, you need to append the class name and . before the this keyword

ActivityClassName.this

Toast either requires the context of the activity on which it is to be displayed or the context of the application

Toast using activity context

Toast.makeText(Activityname.this,"Button pressed",Toast.LENGTH_SHORT).show();

Note: If your Toast is inside any anonymous class, then you need to use ActivityName.this. If that's not the case, simply using this would do the job.

Toast using application context

Toast.makeText(getApplicationContext(),"Button pressed",Toast.LENGTH_SHORT).show();

For toasts, which are short-lived, you can usually use whatever context you want. Typically, you would use the activity context, but application context is fine as well.

So you can use Classname.this Eg:- MainActivity.this or getApplicationContext();

Basically onClick(View v) method is anonymous class which implements method of interface android.view.View.onClickListner so only this keyword of context doesn't belong to anonymous class

so you may define reference of this keyword with related Activity in button onClickListner like below code

 btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d("My app","Button is pressed");
        Toast.makeText(MainActivity.this,"Button pressed",Toast.LENGTH_SHORT).show();  //Change here
    }
});

for more reference check this link

If The activity that you use Called "MyActivity" then you can do the following:

MyActivity.this

This chunk of code will return the this "current" object of outer class this will work for you.

     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("My app","onCreate is called");
    Toast1("onCreate");
    Button btn=(Button)findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("My app","Button is pressed");
            Toast.makeText(MyActivity.this
    ,"Button pressed",Toast.LENGTH_SHORT).show();//here is the working code for you
        }
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!