Android:对超过 1 个按钮使用带有 setOnClickListener/onClick 的 SWITCH 语句? [英] Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

查看:16
本文介绍了Android:对超过 1 个按钮使用带有 setOnClickListener/onClick 的 SWITCH 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 LinearLayout 中有几个按钮,其中 2 个是:

Let's say I have a few buttons in a LinearLayout, 2 of them are:

mycards_button = ((Button)this.findViewById(R.id.Button_MyCards));
exit_button = ((Button)this.findViewById(R.id.Button_Exit));

我在它们两个上都注册了 setOnClickListener():

I register setOnClickListener() on both of them:

mycards_button.setOnClickListener(this);
exit_button.setOnClickListener(this);

如何制作 SWITCH 以区分 Onclick 中的两个按钮?

How do I make a SWITCH to differentiate between the two buttons within the Onclick ?

public void onClick(View v) {
  switch(?????){
    case ???:
      /** Start a new Activity MyCards.java */
      Intent intent = new Intent(this, MyCards.class);
      this.startActivity(intent);
      break;
    case ???:
      /** AlerDialog when click on Exit */
      MyAlertDialog();
      break;
}

推荐答案

使用:

  public void onClick(View v) {

    switch(v.getId()){

      case R.id.Button_MyCards: /** Start a new Activity MyCards.java */
        Intent intent = new Intent(this, MyCards.class);
        this.startActivity(intent);
        break;

      case R.id.Button_Exit: /** AlerDialog when click on Exit */
        MyAlertDialog();
        break;
    }
}

请注意,这在 Android 库项目中不起作用(由于 http://tools.android.com/tips/non-constant-fields),您需要在其中使用以下内容:

Note that this will not work in Android library projects (due to http://tools.android.com/tips/non-constant-fields) where you will need to use something like:

int id = view.getId();
if (id == R.id.Button_MyCards) {
    action1();
} else if (id == R.id.Button_Exit) {
    action2();
}

这篇关于Android:对超过 1 个按钮使用带有 setOnClickListener/onClick 的 SWITCH 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆