我正在制作一个音乐播放器。我想从ListView播放选定的歌曲。但是当我点击listview中的特定项目(歌曲)时。我没有得到我在第二堂课中点击的项目(歌曲)。播放器始终从列表中选择第一首歌曲并播放第一首歌曲。我认为代码中存在问题。请检查并纠正。谢谢
Tab1(发送课程)
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int songIndex = position;
// Starting new intent
Intent in = new Intent(getActivity(), NowPlaying.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
getActivity().setResult(100, in);
// Closing PlayListView
getActivity().finish();
startActivity(in);
}
NowPlaying(接收课程)
/**
* Receiving song index from playlist view
* and play the song
*/
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
currentSongIndex = data.getExtras().getInt("songIndex");
// play selected song
playSong(currentSongIndex);
}
}
答案 0 :(得分:0)
这可能会对你有所帮助 https://developer.android.com/training/basics/intents/result.html
在第一项活动中,您需要拨打startActivityForResult()
而不是startActivity()
。在此之后不要在此活动上致电finish()
根据要返回结果的活动,您只需在结束使用finish()
之前设置结果,该活动就不会调用startActivity()
来调用旧活动。
不要在第二个活动中使用类名作为意图构造函数。用户默认意图构造函数
答案 1 :(得分:0)
传递歌曲的位置
<强> TAB1 强>
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent in = new Intent(getActivity(), NowPlaying.class);
in.putExtra("songIndex", position);
startActivity(in);
getActivity().finish();
}
NowPlaying(接收课程)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name); //insert here you activity's xml layout
currentSongIndex = getExtras().getInt("songIndex");
// currentSongIndex now holds an integer value, the position of the song selected from your list. After that you should call your function to play the specific song
}
答案 2 :(得分:0)
看到有两件事:
如果您想通过Intent
对象传递它并希望在另一个类中接收它,您需要在onCreate
中接收它,如下所示:
在NowPlaying(接收班级)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentSongIndex = getIntent().getStringExtra("songIndex");
}
如果您想在onActivityResult
内完成此操作,那么您的NowPlaying
活动必须已Tab1Activity
与startActivityForResult()
开始。无需在onListItemClick
Tab1
开始活动
醇>
编辑:
你需要了解我的差异:Difference between startActivityForResult() and startActivity()?