I'm having trouble with the following:
I have a spinner with different songs in it. What I would like to do is when you select a song from the spinner, the media player will play that songs. I understand how to do the mediaplayer coding but having trouble linking it. Do I need some sort of value for each song or reference id that the player can then use? Thanks.
The Code that I have (only the spinner):
package com.example.spinnertutorial;
public class SpinnerTutorial extends Activity { /** Called when the activity is first created. */
String[] spinnerItems = {
"Song 1", "Song 2", "Song 3", "Song 4", "Song 5"
};
Spinner sp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_dropdown_item, spinnerItems);
sp = (Spinner)findViewById(R.id.spinner1);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
int item = sp.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have selected the playlist: " +spinnerItems[ item], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){
}
});
} }
If you use the song file names in the spinner, you can retrieve those names ( getSelectedItem()
) and use them directly in MediaPlayer
.
If your Spinner
has the song title or any other string unrelated to the song file name, then use the selected index (using getSelectedItemPosition()
) to retrieve the file name from a second array, or use a HashMap
with song titles and song file names. The Bundle
class is a good option.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.