Android点击事件的三种写法
来源:互联网 发布:原生js图片上传 编辑:程序博客网 时间:2024/05/29 06:43
方式一:在activity的onCreate()方法中,嵌入如下代码:
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
TextView textview = (TextView)findViewById(R.id.textView1);
textview.setText("Button");
}
});
这种方式用findviewbyid通过id实例化出来这个button,然后通过设置button的listener监听对象,并同时实现接口OnClickListenter的OnClick()方法。这种方式的代码量不多,但是在java中,面向对象的思想,关于耦合,模块化它达不到。代码堆叠在一起,比较臃肿。
方式二:让acticity持有TextView,并且新建类Button_Listener实现接口OnClickListener,activity中的代码为:
public class TestOnClickActivity extends Activity {
private TextView textview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
this.textview = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(new Button_Listener(this));
}
public TextView getTextview() {
return this.textview;
}
}
类Button_Listener的代码为:
class Button_Listener implements OnClickListener {
private TestOnClickActivity activity;
public Button_Listener(TestOnClickActivity activity) {
this.activity = activity;
}
@Override
public void onClick(View v) {
TextView textview = activity.getTextview();
textview.setText("你点击了Button");
}
}
方式二:
在方式二中,为了改正方式一的接口实现的不规范,特别重新建立了一个类:Button_Listener。
这种方式代码结构清晰,在为Button加入监听方法是,只需要new Button_Listener(this)即可。但同时,我们也能够发现,因为不属于类TestOnClickActivity,所以类Button_Listener必须通过持有TestOnClickActivity, 将其作为成员。并且,我们需要在TestOnClickActivity 中显示的加入TextView,并书写getTextview()方法,才能够实现我们的程序意图。
虽然代码的模块化,解耦化得到了一定程度上的实现,但换来的结果是代码更多,书写更加繁琐。
方式三:在组件文件main.xml中,对Button加入:
android:onClick="onClick_Event"
在activity中加入以下代码:
public void onClick_Event(View view) {
TextView textview = (TextView)findViewById(R.id.textView1);
textview.setText("Button");
}
在方式三种,我们只需要在TestOnClickActivity 中增加一个成员函数onClick
- Android点击事件的三种写法
- 按钮点击事件的三种写法
- Android点击事件的4种写法
- Android点击事件的四种写法
- android点击事件的四种写法
- Android点击事件的4种写法
- Android点击事件的4种写法
- Android点击事件的四种写法
- Android点击事件的四种写法
- android点击事件的四种写法
- Android 点击事件的4种写法
- [Android] 点击事件的四种写法
- Android----点击事件的四种写法
- Android开发之onClick(鼠标点击)事件的三种写法
- Ext.Button点击事件的三种写法
- Ext.Button点击事件的三种写法及比较
- Ext.Button点击事件的三种写法及比较
- Android:onClick事件的三种写法
- RecyclerView的Adapter的抽取
- offsetof' was not declared in this scope
- 100+ 超全的web开发工具和资源
- coyote
- Pascal's Triangle
- Android点击事件的三种写法
- C++ 构造器
- 第十六周项目一 a阅读程序(1)
- js 输出html的表格数据到 excel
- 用Qt 调用GDB调试 Arm程序 详细步骤----可单步执行每一行
- HTML页面为什么设置了UTF-8仍然中文乱码
- TCP 的那些事儿(下)
- 【Java学习-J.160601.0.20】Servlet 基础三 dao的封装
- ssh client algorithm negotiation failed