android - ToggleButton makes mediaplayer play twice at once -
i have mediaplayer plays music in activity below. thing is, music transfers other activities , thats fine. when start music, go activity , come activity below, togglebutton has changed on off. therefore, if click on togglebutton, music starts again though music still playing music playing twice @ once! how make togglebutton know music playing when come activity, togglebutton "on" beginning? it's "off" default.
public class spelaactivity extends activity { @override protected void oncreate (bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_spela); final mediaplayer mediaplayer = mediaplayer.create(getbasecontext(), r.raw.ljudfil); togglebutton musikknapp = (togglebutton) findviewbyid(r.id.togglemusik); musikknapp.setoncheckedchangelistener (new compoundbutton.oncheckedchangelistener() { public void oncheckedchanged(compoundbutton buttonview, boolean ischecked) { if (ischecked) { mediaplayer.start(); } else { mediaplayer.pause(); } } }); mediaplayer.setoncompletionlistener(new oncompletionlistener() { @override public void oncompletion(mediaplayer mediaplayer) { mediaplayer.release(); } }); } }
you need save togglebutton state. try code:
public class mainactivity extends activity { private togglebutton togglebutton; private static bundle bundle = new bundle(); @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); togglebutton = (togglebutton)findviewbyid(r.id.togglebutton1); } @override public void onpause() { super.onpause(); bundle.putboolean("togglebuttonstate", togglebutton.ischecked()); } @override public void onresume() { super.onresume(); togglebutton.setchecked(bundle.getboolean("togglebuttonstate",false)); }
Comments
Post a Comment