从检索到的歌曲列表中播放歌曲

时间:2015-11-30 14:33:31

标签: android android-mediaplayer

这是我检索设备上歌曲列表的代码。我想播放选定的歌曲。无法弄清楚如何使用onItemClickListener来完成它。我如何在另一项活动中这样做?

public class SongsFragment extends Fragment {


public SongsFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view=inflater.inflate(R.layout.fragment_songs, container, false);
    ListView audioView = (ListView)view.findViewById(R.id.songView);
    ArrayList<String> audioList = new ArrayList<>();
    String[] proj = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME};
    final Cursor audioCursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);

    if (audioCursor != null) {
        if (audioCursor.moveToFirst()) {
            do {
                int audioIndex = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);

                audioList.add(audioCursor.getString(audioIndex));
            } while (audioCursor.moveToNext());
        }
    }
    audioCursor.close();

    ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, audioList);
    audioView.setAdapter(adapter);

        return view;

    }

1 个答案:

答案 0 :(得分:0)

使用audioView.setOnItemClickListener(new AdapterView.OnItemClickListener(){     @覆盖     public void onItemClick(AdapterView parent,View view,int position,long id){         对象歌曲= list.getItemAtPosition(position);         // TODO播放歌曲    } });

基本上,当您从列表视图中单击一个歌曲项目时,您将获得所选歌曲的值,然后您可以播放它。