Android 如何将歌曲索引发送到自定义音乐播放器?
因此,我对android编程非常陌生,我想知道如何将歌曲索引从库Android 如何将歌曲索引发送到自定义音乐播放器?,android,listview,android-fragments,arraylist,Android,Listview,Android Fragments,Arraylist,因此,我对android编程非常陌生,我想知道如何将歌曲索引从库Fragment发送到播放器Fragment,然后使用该索引自动播放歌曲。到目前为止,对于我所拥有的代码,单击ListItem时不会发生任何事情。我什么都不是。它甚至没有像预期的那样砸到我身上。这是代码 LibraryFragment public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Fragment
发送到播放器Fragment
,然后使用该索引自动播放歌曲。到目前为止,对于我所拥有的代码,单击ListItem
时不会发生任何事情。我什么都不是。它甚至没有像预期的那样砸到我身上。这是代码
LibraryFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_library, container, false);
songView = (ListView)rootView.findViewById(R.id.song_list);
songList = new ArrayList<>();
getSongList();
Collections.sort(songList, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Getting list item index
int songIndex = position;
// Starting new intent
Intent in = new Intent(getActivity().getApplicationContext(), LibraryFragment.class);
// Sending songIndex to Player Fragment
in.putExtra("songIndex", songIndex);
getActivity().setResult(100, in);
}
});
SongAdapter songAdt = new SongAdapter(getActivity(), songList);
songView.setAdapter(songAdt);
return rootView;
}
@Override
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 100){
currentSongIndex = data.getExtras().getInt("songIndex");
playSong(currentSongIndex);
}
}
任何帮助都将不胜感激!干杯 不能对片段使用意图,它们不可启动 另外,您认为
getActivity().setResult(100,in)是什么代码>是什么?你肯定用错了
请阅读有关通信的片段
详细信息
- 您的
LibraryFragment
需要定义一个接口,例如
公共接口库Listener{
void onIndexSelected(整数索引)
}
- 您的活动必须实现此接口。在这个实现中,它必须将索引传递给
PlayerFragment
,后者应该定义一个公共方法来实现这一点
- 现在您的LibraryFragment可以调用
((LibraryListener)getActivity()).onIndexSelected(index)代码>
您不能对片段使用意图,它们不可启动
另外,您认为getActivity().setResult(100,in)是什么代码>是什么?你肯定用错了
请阅读有关通信的片段
详细信息
- 您的
LibraryFragment
需要定义一个接口,例如
公共接口库Listener{
void onIndexSelected(整数索引)
}
- 您的活动必须实现此接口。在这个实现中,它必须将索引传递给
PlayerFragment
,后者应该定义一个公共方法来实现这一点
- 现在您的LibraryFragment可以调用
((LibraryListener)getActivity()).onIndexSelected(index)代码>
啊,谢谢。你知道我将如何发送索引吗?我仍然有点困惑。我提供了一个简短的例子。如果您既不了解这一点,也不了解文档中的示例,那么您应该后退一步,学习Java中的接口和类型转换是如何工作的。啊,谢谢。你知道我将如何发送索引吗?我仍然有点困惑。我提供了一个简短的例子。如果您既不了解这一点,也不了解文档中的示例,那么您应该后退一步,了解Java中接口和类型转换是如何工作的。