问题描述
其中之一就是实现了Android的OnClickListener接口最佳方式。
/ * - 首先 - * /
公共类EmployeeActivity扩展活动实现OnClickListener
{ / **当第一次创建活动调用。 * /
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main); 按钮btnUpdate =(按钮)findViewById(R.id.btnUpdate);
按钮btnEdit =(按钮)findViewById(R.id.btnEdit); btnUpdate.setOnClickListener(本);
btnEdit.setOnClickListener(本); @覆盖
公共无效的onClick(视图v){ 如果(V == btnAddEmployee)
{}
如果(V == btnUpdate)
{}
}
/ - 二 - /
公共类EmployeeActivity延伸活动{ / **当第一次创建活动调用。 * /
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main); 按钮btnUpdate =(按钮)findViewById(R.id.btnUpdate);
按钮btnEdit =(按钮)findViewById(R.id.btnEdit); btnUpdate.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根 }
}); btnEdit.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根 }
});
}
}
This depends solely on what fits best for you as the developer. They all work the same and you even have another option to declare onClick
in xml. I like the first especially if you will have multiple Button
s that you want to share functionality. But a better way to do the first is to switch
on the id
of the View
being clicked. Something like
@Override
public void onClick(View v) {
int id = v.getId();
switch (id)
{
case R.id.btnUpdate:
// do work
break;
case R.id.btnEdit
// do work for edit button
break;
}
// put shared functionality code like starting an Activity, calling a method, etc...
}
The second I like to use if there is only one or two Button
s and they have completely different functionality. I think this way makes the code look more cluttered and messy if you have too many Button
s. But these all work the same and won't change the performance of your app.
这篇关于哪一个是Android中,以实现OnClickListener最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!