Button单击事件的四种写法:
1、第一种写法:匿名内部类
附上代码:
public class MainActivity extends Activity{
private Button btn ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn) ;
//第一种写法:匿名内部类
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "我弹出来了", 0).show() ;
}
}) ;
}
}
2、创建内部类
public class MainActivity extends Activit{
private Button btn ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn) ;
btn.setOnClickListener(new MyListener() ) ;
}
class MyListener implements View.OnClickListener{
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "我弹出来了哈哈", 0).show() ;
}
}
}
3、用窗体实现监听器
public class MainActivity extends Activity implements View.OnClickListener {
private Button btn ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn) ;
//第三种:用窗体实现监听器
btn.setOnClickListener(this) ;
}
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "哈哈,我来了", 0).show() ;
}
}
4、通过属性声明
public class MainActivity extends Activity{
private Button btn ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn) ;
}
//第四种: 通过属性声明
public void click(View view){
Toast.makeText(MainActivity.this, "哈哈哈哈哈", 0).show() ;
}
}
以上有背景色的部分为各种方法的关键代码。
本文出自 “初学者” 博客,请务必保留此出处http://10154241.blog.51cto.com/10144241/1663859
原文地址:http://10154241.blog.51cto.com/10144241/1663859