[英]the role of “this” in TextView textView = new TextView(this);
The reason you need this
when creating a TextView
is because one of the the constructors of TextView
(the one that you're calling) takes a Context
object as a parameter. 你需要的原因
this
创建时TextView
是因为一个构造函数TextView
(一个你调用)需要Context
对象作为参数。
That basically means you must give TextView
a Context
in order to create it. 基本上,这意味着您必须为
TextView
一个Context
才能创建它。
Where do you get this context from? 您从何处获得此上下文? Well, an activity is a kind of context (
Activity
is a subclass of Context
)! 好吧,活动是一种上下文(
Activity
是Context
的子类)! And you're creating the TextView
in an activity class right? 您是在活动类中创建
TextView
吗? So just use this activity as the context! 因此,只需将此活动用作上下文!
Got it? 得到它了? Use this activity as the context for the
TextView
! 将此活动用作
TextView
的上下文! That's why you put this
in there. 这就是为什么你把
this
放在那里。 this
refers to the object that the code is currently running on. this
是指代码当前正在其上运行的对象。
Since this
refers to an object created from the class, you can't use this
in a static method because a the code in a static method does not run on any object. 由于
this
是指从类创建的对象,因此您不能在静态方法中使用this
,因为静态方法中的代码不会在任何对象上运行。
Another use of this
is in constructors: this
方法的另一种用法是在构造函数中:
class MyClass {
private int a, b;
public MyClass(int a, int b) {
this.a = a;
this.b = b;
}
}
Since the compiler can't know which a
or b
you mean, you must add this
to refer the a
that's in the class. 由于编译器无法知道您的意思是
a
或b
,因此必须添加this
以引用类中的a
。
this
refers to the current object's instance that was invoked or initialized. this
是指被调用或初始化的当前对象的实例。
See: What does "this" mean? 请参阅: “这个”是什么意思?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.