以实现OnClickListener最好的方法

以实现OnClickListener最好的方法

本文介绍了哪一个是Android中,以实现OnClickListener最好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其中之一就是实现了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 Buttons 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 Buttons and they have completely different functionality. I think this way makes the code look more cluttered and messy if you have too many Buttons. But these all work the same and won't change the performance of your app.

这篇关于哪一个是Android中,以实现OnClickListener最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 15:56