使用Switch语句处理按钮点击事件

19

我试图理解视图(Views)、监听器(Listeners)等概念。我有一个Activity,里面有两个按钮: buttonplay和buttonstop。我的问题是我无法完全理解Views和Listeners,以至于无法生成一个可工作的switch语句。

例如,我希望创建一个单一的Listener,并在其中确定哪个按钮被点击。然后使用所点击按钮的ID作为switch语句的参数。但我在网上找到的所有资料都似乎是为每个按钮使用单独的监听器,然后将View作为参数传递给switch语句。

我知道下面的代码不正确,但我想知道需要做哪些更改才能实现上述目标。

我希望根据所点击的按钮来控制MediaPlayer。我已经有:

   Button b1 = (Button) findViewById(R.id.buttonplay);       
    b1.setOnClickListener(new View.OnClickListener()         
    {

        public void onClick(View v) {
           // Perform action on click
          switch(v.getId()) {
          case R.id.buttonplay:
          //Play voicefile
          MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
          break;
          case R.id.buttonstop:
          //Stop MediaPlayer
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
          break;
         }
   }
    });

我希望最终能够以最简单的方式切换任何被点击的按钮。我相信我的困惑很大程度上源于在这种情况下使用onClickListeners和Views的方式。

8个回答

43

实现这个功能的一种方法是让你的类实现OnClickListener,然后像这样将它添加到你的按钮上:

示例:

//make your class implement OnClickListener
public class MyClass implements OnClickListener{

        ...

        //Create your buttons and set their onClickListener to "this"
        Button b1 = (Button) findViewById(R.id.buttonplay);   
        b1.setOnClickListener(this);

        Button b2 = (Button) findViewById(R.id.buttonstop);   
        b2.setOnClickListener(this);

        ...

        //implement the onClick method here
        public void onClick(View v) {
           // Perform action on click
          switch(v.getId()) {
            case R.id.buttonplay:
              //Play voicefile
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
              break;
            case R.id.buttonstop:
              //Stop MediaPlayer
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
              break;
          }
       }
}

了解更多信息,请参见 Android 开发者 > 处理 UI 事件


这可能是我正在寻找的东西...不过有一个问题:我的类是APK中的第三个Activity,因此我已经定义它为:public class Activity3 extends Activity,因为它是一个单独的activity..在这个Activity类中,我可以使用implements吗? - user615525
@user615525,是的,你应该能够将它声明为:public class Activity3 extends Activity implements OnClickListener - dogbane

6

只需更改类(我假设它是主Activity)以实现View.OnClickListener,并在onClick方法中放置您想要放置的通用onClick操作:

public class MediaPlayer extends Activity implements OnClickListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    Button b1 = (Button) findViewById(R.id.buttonplay);       
    b1.setOnClickListener(this);
    //{YOUR APP}
}


@Override
public void onClick(View v) {
    // Perform action on click
    switch(v.getId()) {
    case R.id.buttonplay:
        //Play voicefile
        MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
        break;
    case R.id.buttonstop:
        //Stop MediaPlayer
        MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
        break;
    }

}}

我从这个视频中获取了信息:http://www.youtube.com/watch?v=rm-hNlTD1H0。这对初学者很有帮助。

5

嗨,使用switch case很容易在按钮之间进行切换:

 package com.example.browsebutton;


    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

        public class MainActivity extends Activity implements OnClickListener {
        Button b1,b2;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                b1=(Button)findViewById(R.id.button1);

                b2=(Button)findViewById(R.id.button2);
                b1.setOnClickListener(this);
                b2.setOnClickListener(this);
            }



            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 int id=v.getId();
                 switch(id) {
                    case R.id.button1:
                  Toast.makeText(getBaseContext(), "btn1", Toast.LENGTH_LONG).show();
                //Your Operation

                  break;

                    case R.id.button2:
                          Toast.makeText(getBaseContext(), "btn2", Toast.LENGTH_LONG).show();


                          //Your Operation
                          break;
            }

        }}

3

我犯了一个错误,就是在主类声明中没有包含“implements OnClickListener”。这是一个示例代码,清楚地说明了在点击时使用switch case的用法。根据按下的按钮,代码会更改背景颜色。 希望这可以帮助您。

public class MainActivity extends Activity  implements OnClickListener{


TextView displayText;
Button cred, cblack, cgreen, cyellow, cwhite;
LinearLayout buttonLayout;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    cred = (Button) findViewById(R.id.bred);
    cblack = (Button) findViewById(R.id.bblack);
    cgreen = (Button) findViewById(R.id.bgreen);
    cyellow = (Button) findViewById(R.id.byellow);
    cwhite = (Button) findViewById(R.id.bwhite);
    displayText = (TextView) findViewById(R.id.tvdisplay);
    buttonLayout = (LinearLayout) findViewById(R.id.llbuttons);

    cred.setOnClickListener(this);
    cblack.setOnClickListener(this);
    cgreen.setOnClickListener(this);
    cyellow.setOnClickListener(this);
    cwhite.setOnClickListener(this);
}

@Override
protected void onClick(View V){
    int id=V.getId();
    switch(id){
    case R.id.bred:
        displayText.setBackgroundColor(Color.rgb(255, 0, 0));
        vanishLayout();
        break;
    case R.id.bblack:
        displayText.setBackgroundColor(Color.rgb(0, 0, 0));
        vanishLayout();
        break;
    case R.id.byellow:
        displayText.setBackgroundColor(Color.rgb(255, 255, 0));
        vanishLayout();
        break;
    case R.id.bgreen:
        displayText.setBackgroundColor(Color.rgb(0, 255, 0));
        vanishLayout();
        break;
    case R.id.bwhite:
        displayText.setBackgroundColor(Color.rgb(255, 255, 255));
        vanishLayout();
        break;
    }
}

3
我发现最简单的方法是在xml中为每个按钮设置onClick。
<Button
android:id="@+id/vrHelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_menu_help"
android:onClick="helpB" />

然后你可以像这样使用 switch case

  public void helpB(View v) {
    Button clickedButton = (Button) v;
    switch (clickedButton.getId()) {
      case R.id.vrHelp:
        dosomething...
        break;

      case R.id.coHelp:
        dosomething...
        break;

      case R.id.ksHelp:
        dosomething...
        break;

      case R.id.uHelp:
        dosomething...
        break;

      case R.id.pHelp:
        dosomething...
        break;
    }
  }

0

我使用Butterknife和switch-case来处理这种情况:

    @OnClick({R.id.button_bireysel, R.id.button_kurumsal})
        public void onViewClicked(View view) {
            switch (view.getId()) {


                case R.id.button_bireysel:
 //Do something

                    break;
                case R.id.button_kurumsal:

     //Do something

                    break;

            }
        }

但是问题在于没有默认情况,而 switch 语句会跳过。


0

我认为你遗漏的一件事是你没有声明停止按钮 b2,你只声明并初始化了 b1。


目前你的回答不够清晰,请编辑并添加更多细节以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

0
    XML CODE FOR TWO BUTTONS  
     <Button
            android:id="@+id/btn_save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SAVE"
            android:onClick="process"
            />
        <Button
            android:id="@+id/btn_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SHOW"
            android:onClick="process"/> 

  Java Code
 <pre> public void process(View view) {
            switch (view.getId()){
                case R.id.btn_save:
                  //add your own code
                    break;
                case R.id.btn_show:
                   //add your own code
                    break;
            }</pre>

这个怎么解决问题的?稍微解释一下会更好地完善你的回答。 - Selim Yildiz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接