开发者

Select Song in Spinner then play the song Android development

开发者 https://www.devze.com 2023-03-12 09:09 出处:网络
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 under

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.getS开发者_开发知识库electedItemPosition();
            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.

0

精彩评论

暂无评论...
验证码 换一张
取 消