简体   繁体   English

如何自动使用班级名称?

[英]How can I automatically use the name of the class?

在下面的代码中,我可以代替Play.this编写什么,以便它可以自动使用使用该类的名称,而无需编写名称(在本例中为“ Play”) AlertDialog.Builder builder = new AlertDialog.Builder(Play.this);

There's no reason to use Play.this in code being part of Play class. 没有理由在Play类的代码中使用Play.this Just use this : 只需使用this

AlertDialog.Builder builder = new AlertDialog.Builder(this);

However if you want to do that from your inner class, then you need this will not point to Context subclass, so you can ie create member in your parent class, ie: 但是,如果你想要做的是从你的内部类,那么你就需要this不会指向Context的子类,这样你就可以即在你的父类,即创建成员:

Context mContext;

initialize it in ie onCreate() : 初始化它,即onCreate()

mContext= this;

and use mContext from your listener's code 并从您的侦听器的代码中使用mContext

AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

There are other things to think before set the context (this). 设置上下文(此)之前,还需要考虑其他事项。

First case - If you are in a class that extends a context in its base like Activity/Services, and you are NOT in a inner class, you can use just "this" 第一种情况-如果您所在的类在其基础中扩展了上下文(如“活动/服务”),而您不在内部类中,则可以仅使用“ this”

Second - If you are in a class that extends a context in its base like Activity/Services, and you are in a inner class, you can use (Play.this), because the "this" in this case, is about the inner class. 第二-如果您是在一个类中扩展了上下文(如Activity / Services),并且您在一个内部类中,则可以使用(Play.this),因为在这种情况下,“ this”与内部类。

Third - If you are in another class that does not have a context, you can pass it in constructor or method like: 第三-如果您在另一个没有上下文的类中,则可以在构造函数或方法中传递它,例如:

class Test {
   public void createBuilder(Context context) {
      AlertDialog.Builder builder = new AlertDialog.Builder(context);
   }
}

I think what you are looking for is this.getClass().getName() . 我认为您正在寻找的是this.getClass().getName() If you want just the unqualified name, use this.getClass().getSimpleName() instead. 如果只需要非限定名称,请改用this.getClass().getSimpleName() I know very little about Android specifically, but that's how you would do it in Java in general. 我对Android知之甚少,但是一般来说,这就是用Java做到的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM