android中this的用法,求详解,不是很懂,一定要详细哦解决思路
android中this的用法,求详解,不是很懂,一定要详细哦
[b]public class first extends Activity {
/** Called when the activity is first created. */
private Button button=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button=(Button)findViewById(R.id.firstbutton);
button.setOnClickListener(new buttonListener());
}
class buttonListener implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.setClass(first.this, second.class);
first.this.startActivity(intent);
}
}
}
------解决方案--------------------
this指的是当前对象,你在一个类里调用this,就是调用这个类的对象,在你上面的代码里,因为你在一个内部类里调用this,这个this所指的是这个内部类,而程序需要的是外部类的对象,所以使用 类名.this,这是因为内部类可以直接访问外部类的属性和方法
------解决方案--------------------
buttonListener 是内部类 如果此处用this就指buttonListener
此处用first.this 是值first
这是因为要在内部类里调用外部类的方法
[b]public class first extends Activity {
/** Called when the activity is first created. */
private Button button=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button=(Button)findViewById(R.id.firstbutton);
button.setOnClickListener(new buttonListener());
}
class buttonListener implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.setClass(first.this, second.class);
first.this.startActivity(intent);
}
}
}
------解决方案--------------------
this指的是当前对象,你在一个类里调用this,就是调用这个类的对象,在你上面的代码里,因为你在一个内部类里调用this,这个this所指的是这个内部类,而程序需要的是外部类的对象,所以使用 类名.this,这是因为内部类可以直接访问外部类的属性和方法
------解决方案--------------------
buttonListener 是内部类 如果此处用this就指buttonListener
此处用first.this 是值first
这是因为要在内部类里调用外部类的方法