匿名类中的活动名称是什么 [英] what is the activity name in anonymous class

查看:40
本文介绍了匿名类中的活动名称是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我是 android 的新手,我对活动上下文中的这个关键字感到困惑.这是一个代码片段,当按下按钮时,它会简单地打印到屏幕上.但工作室提出了一个问题.

Hello I'm new to android and I'm confused with this keyword in activity contexts. Here is a code snippet which simply prints to the screen when a button is pressed. But the studio is raising an issue.

 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(this,"Button pressed",Toast.LENGTH_SHORT).show();//Here is a error
        }
    });
}

如何知道 this 关键字引用的是哪个活动或类?

How to know which activity or class the this keyword referencing?

推荐答案

匿名类内部,this 指的是匿名类的块.要引用包含匿名类的Activity类,需要在this关键字

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 要么需要显示它的活动的上下文,要么需要应用程序的上下文

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

使用活动上下文的 Toast

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

注意:如果您的 Toast 在任何匿名类中,那么您需要使用 ActivityName.this.如果不是这种情况,只需使用 this 即可完成这项工作.

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 使用应用程序上下文

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

这篇关于匿名类中的活动名称是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆