Android应用开发中关于this.context=context的理解

  在Android应用开发中,有的类里面需要声明一个Context的成员变量,然后还需要在该类的构造函数中加上this.context=context;这行代码。为什么要这么写呢?

  先看下面这个例子,这是我在百度空间看到的:

Button button=new Button(this);

括号里的this当然就是本质上Context,其指向的就是当前的Activity,原因形象点说就是Button为了能相应各种操作,记得让Android系统知道自己是属于哪个Activity,这个信息是必须的,因为只有这样Android才会对其进行管理,比如相应onClick()事件,否则Android连这个Button属于哪个Activity都不知道,怎么响应?。

this的用法this.name=name 这个什么意思啊 具体点我有点狠难理解

public Employee(string name, string alias) {

 // Use this to qualify the fields, name and alias:

  this.name = name;

  this.alias = alias;

 }

this的用法this.name=name 这个什么意思啊 具体点我有点狠难理解

这是个构造函数this.name指当前类的属性,后一个name是构造函数中的参数 这就是给类中的属性赋值 .

这样写就清楚了 public Employee(string strName, string strAlias) {

 // Use this to qualify the fields, name and alias:

 this.name = strName;

this.alias = strAlias;

 }

this就是当前类的实例对象,在这就是MainActivity,getApplicationContext获取的是Application对象他们都是Context的子类,后者是全局上下文,生命周期是整个程序运行期间,并且是单例的。
其中Application是可以自定义的,一般用来存全局变量,实现Application的子类,在配置文件中声明,需要使用的时候getApplicationContext()强转成你自定义的类。

 

java中this作为参数

1. this是指当前对象自己。
当在一个类中要明确指出使用对象自己的的变量或函数时就应该加上this引用。如下面这个例子中:
public class Hello {
    String s = "Hello";
    public Hello(String s) {
        System.out.println("s = " + s);
        System.out.println("1 -> this.s = " + this.s);
        this.s = s;
        System.out.println("2 -> this.s = " + this.s);
    }

    public static void main(String[] args) {
        Hello x = new Hello("HelloWorld!");
    }
}
运行结果:
s = HelloWorld!
1 -> this.s = Hello
2 -> this.s = HelloWorld!

 

public class AccpTercher1 {

 private String name; // 教员

 private int age;// 年龄

 private String education;//学历

 private String position;//职位

 

 public AccpTercher1(String name,int age,String education,String position){

  this.name=name;

  this.age=age;

  this.education=education;

  this.position=position;

 }

this.name指当前类的属性,后一个name是构造函数中的参数 这就是给类中的属性赋值

     在这个例子中,构造函数Hello中,参数s与类Hello的变量s同名,这时如果直接对s进行操作则是对参数s进行操作。若要对类Hello的成员变量s进行操作就应该用this进行引用。运行结果的第一行就是直接对构造函数中传递过来的参数s进行打印结果; 第二行是对成员变量s的打印;第三行是先对成员变量s赋传过来的参数s值后再打印,所以结果是HelloWorld!

2. 把this作为参数传递
当你要把自己作为参数传递给别的对象时,也可以用this。如:
public class A {
    public A() {
        new B(this).print();
    }

    public void print() {
        System.out.println("Hello from A!");
    }
}
public class B {
    A a;
    public B(A a) {
        this.a = a;
    }
    public void print() {
        a.print();
        System.out.println("Hello from B!");
    }
}
运行结果:
  Hello from A!
  Hello from B!  
在这个例子中,对象A的构造函数中,用new B(this)把对象A自己作为参数传递给了对象B的构造函数。

当然,如果本类中调用其他类的方法,该方法可以把这个类传过去,比如:

public class Dog{

public String name;

public Dog(String name){

this.name = name;

}

}

Man man = new Man();

man.parseDog(this);

你可能感兴趣的:(Android应用开发中关于this.context=context的理解)