gpt4 book ai didi

java - Android 中切换状态播放、暂停、停止

转载 作者:行者123 更新时间:2023-12-01 04:46:40 29 4
gpt4 key购买 nike

我正在创建一个带有两个按钮开始/暂停和停止按钮的媒体播放器,当我第一次开始播放时它工作正常。但是,当我尝试在一次停止后启动时,我需要单击启动/暂停按钮两次。

我不明白这种行为。

下面是我的 onclick 代码:

public void click(View view){
int id = view.getId();

try {
mPlayer.setDataSource(PATH);
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


switch(id){
case R.id.btnPlay:
synchronized(this){

if(!isStarted){
btnPlay.setBackgroundResource(R.drawable.pause);
isStarted=true;
mPlayer.start();
System.out.println("Play");

} else{
System.out.println("Pause");
isStarted = false;
btnPlay.setBackgroundResource(R.drawable.play);
mPlayer.pause();
}
}
return;
case R.id.btnStop :
synchronized(this){

if(mPlayer!=null){
System.out.println("Stop");
mPlayer.stop();
isStarted = false;
btnPlay.setBackgroundResource(R.drawable.play);
}
}

这是我的布局 xml 文件:

    <View
android:layout_width="0dip"
android:layout_height="0dip"
android:layout_weight="1" />
<Button
android:id="@+id/btnStop"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/stop"
android:onClick="click" />



<Button
android:id="@+id/btnPlay"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/play"
android:onClick="click" />

<View
android:layout_width="0dip"
android:layout_height="0dip"
android:layout_weight="1" />

<View
android:layout_width="0dip"
android:layout_height="0dip"
android:layout_weight="1" />

</LinearLayout>

请让我知道您的建议。

谢谢

安缦

最佳答案

不确定是否可以直接解决您的问题,但是您不应该在每个 switch case 的末尾添加一个 break; 吗?想将其放在评论中,但我还没有足够的代表,抱歉。​​

关于java - Android 中切换状态播放、暂停、停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15717003/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com