Getting a variable out of a Public Void (Android)
I have this code:
hubSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
开发者_StackOverflow final MediaPlayer mp2 = MediaPlayer.create(Textbox.this, R.raw.hero);
mp2.start();
}
public void onNothingSelected(AdapterView<?> parentView) {
}
});
(The code basically runs when a new item is selected of a spinner and then plays a song, which later will be a variable based on what was picked, but I'm fine as it is for now).
Problem: I want to be able to use 'mp2' out of this public void, (I want a button which pauses it). How can I do this?
Move the variable mp2
to the instance of the parent class. This will keep a running reference to it which you can interact with whenever you please. You will need to remove the final
qualifier though if MediaPlayer.create(...)
will be called more than once and stored.
edit:
I was referring to something along the lines of this:
class SomeClass {
private MediaPlayer mp2 = null;
private void whateverFunctionYouAreIn() {
hubSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
SomeClass.this.mp2 = MediaPlayer.create(Textbox.this, R.raw.hero);
SomeClass.this.mp2.start();
}
public void onNothingSelected(AdapterView<?> parentView) {}
});
//TODO: put this in an onClickListener:
if (this.mp2 != null) {
this.mp2.pause();
}
}
}
I'm not sure what happens when you call MediaPlayer.create(Textbox.this, R.raw.hero)
, but assuming it has no immediate effects, you can just create the object outside of the listener.
Edit1: OK, then how about this?
MediaPlayer currentPlayer;
methodA()
{
hubSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id)
{
MediaPlayer mp2 = MediaPlayer.create(Textbox.this, R.raw.hero);
mp2.start();
setPlayer(mp2);
}
public void onNothingSelected(AdapterView<?> parentView) {
}
});
setMediaPlayer(MediaPlayer player)
{
currentPlayer = player;
}
精彩评论