使用 Switch 语句处理按钮点击 [英] Using Switch Statement to Handle Button Clicks
问题描述
我正在尝试围绕视图、侦听器等进行思考.我有一个带有 2 个按钮的活动:buttonplay 和 buttonstop.我的问题是我无法完全围绕 Views 和 Listeners 生成一个有效的 switch 语句.
I'm trying to wrap my head around Views, Listeners etc. I have an Activity with 2 Buttons: buttonplay and buttonstop. My problem is I can't wrap my head around the Views and Listeners completely enough to generate a working switch statement.
例如,我想创建一个 SINGLE Listener 并以某种方式使用它来确定单击了哪个按钮.然后以某种方式使用在我的 switch 语句中单击的按钮的 ID,但我在网上找到的所有内容似乎都对每个按钮使用了单独的侦听器,然后以某种方式使用 View 作为 Switch 语句的参数.
For example, I would LIKE to create a SINGLE Listener and somehow use it to determine which button is clicked. Then somehow use the ID of the button clicked in my switch statement, But everything I find online seems to use SEPARATE listeners for every button and then somehow use the View as the argument to the Switch statement.
我意识到下面的代码不正确,但我正在寻找完成上述操作所需的更改.
I realize the code below is not correct, but am looking for what changes I would need to accomplish the above.
我想根据单击的按钮来控制 MediaPlayer.我有:
I want to control the MediaPlayer depending on which button is clicked. I have:
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 的方式.
Ultimately I would like the most straighforward way to switch on whatever button is clicked. I believe a big part of my confusion stems from the way onClickListeners and Views are used in this context.
推荐答案
实现此目的的一种方法是让您的类实现 OnClickListener,然后将其添加到您的按钮中,如下所示:
One way of achieving this is to make your class implement OnClickListener and then add it to your buttons like this:
示例:
//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 事件.
For more information see Android Developers > Handling UI Events.
这篇关于使用 Switch 语句处理按钮点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!