简体   繁体   English

TextView中的“ this”的角色textView = new TextView(this);

[英]the role of “this” in TextView textView = new TextView(this);

I am new to Android programming. 我是Android编程的新手。 I want to know that in this code what does the this in 我想知道,在这个代码什么是this

TextView textView = new TextView(this); 

this would point to which class or method? 这将指向哪个类或方法? I copied this code from here . 我从这里复制了这段代码。

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 )! 好吧,活动是一种上下文( ActivityContext的子类)! 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. 由于编译器无法知道您的意思是ab ,因此必须添加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.

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