[英]Quick 'this' Keyword Query - Help Appreicated
因此,基本上很难理解java中'this'关键字的用法。 阅读了大约五本教程,尽管不是很好。 有人可以快速解释一下与以下代码相关的用法吗? 这是一个android系统,它为Button类型的b分配一个xml按钮(btn_confirm)。
Button b = (Button)this.findViewById(R.id.btn_confirm);
b.setonclickListener(this);
完整代码:
public class dic_tut2 extends Activity implements onclickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button)this.findViewById(R.id.btn_confirm);
b.setonclickListener(this);
}
public void onclick(View v) {
TextView tv = (TextView)this.findViewById(R.id.tv_welcome);
EditText et = (EditText)this.findViewById(R.id.txt_name);
String text = "Hello, " + et.getText().toString() + ".\n\n";
text += "Welcome to android development. :)";
tv.setText(text);
}
}
this
是指您在其中使用该类的当前实例。例如:
class A {
public void f() {
A obj = this; // current instance of A
}
}
所以如果以后我创建一个A的实例:
public static void main(String[] args) {
A a = new A();
a.f(); // the 'this' inside f() is actually 'a'.
}
所以你的代码:
b.setonclickListener(this);
将按钮b的onclickListener设置为您所在类的当前实例(从中调用该方法的实例)。
编辑 :好的,这是一个完整的示例:
class A {
public char c;
public A(char c) { this.c = c; }
public void f() {
System.out.println(this.c);
}
}
public static void main(String[] args) {
A a = new A('a');
a.f(); // prints 'a' because 'this' inside f() is actually object 'a'.
A b = new A('b');
b.f(); // prints 'b' because 'this' inside f() is actually object 'b'.
}
在您看到的示例中,该类很可能是活动类。 像这样:
class MainActivity extends Activity implements OnClickListener {
@Override
protected onCreate(Bundle bundle) {
Button b = (Button)this.findViewById(R.id.btn_confirm);
b.setOnClickListener(this);
}
@Override
public onClick(View v) {
// Do something!
}
}
这是可能的,因为对象“ this”既是一个活动,它的视图中可以有一个按钮,而且还实现了OnClickListener,它允许单击该按钮时调用该按钮的onClick方法。 通过为按钮的setOnClickListener函数提供对自身的引用来完成此操作。
b.setonclickListener(this);
这意味着b
的点击侦听器是this
:当前对象。 在这种情况下,这是您的Activity
。
该Activity
实现了OnClickListener
,它提供了onclick
方法。
您基本上是在说“按钮,当您单击按钮时,这里是处理它的方法-您可以使用自己内部包含的实现来处理它。”
它不会是this
,它可能是任何东西,实现OnClickListener
。 通过将实现保留在Activity
本地,您可以轻松访问其( Activity
的)成员变量(在这种情况下不需要使用)。
在onclick
处理程序中, this
引用是多余的-您可以在没有this
情况下访问findViewById
方法。 无需限定符即可访问成员方法和变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.