我想创建一个非常简单的应用程序,显示一个歌曲列表,当点击歌曲它打开一个新的活动,以显示该歌曲的播放雕像,我几乎创建它,但当我点击播放按钮它不播放。
第一项活动:
private Button buttonPlayStop;
private MediaPlayer mMediaPlayer;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
final ArrayList<Songs> songslist = new ArrayList<Songs>();
songslist.add(new Songs("hhhhh", "cHU CHU ", R.drawable.mimi, R.raw.hhh));
songslist.add(new Songs("hhhh", "cHU CHU ", R.drawable.jes1s, R.raw.hhh));
songslist.add(new Songs("hhhh", "cHU CHU ", R.drawable.matt, R.raw.hhh));
songslist.add(new Songs("hhhhh", "cHU CHU ", R.drawable.freind, R.raw.hhh));
songslist.add(new Songs("hhhhh", "cHU CHU ", R.drawable.joe, R.raw.hhh));
songslist.add(new Songs("hhhhh ", "cHU CHU ", R.drawable.bada, R.raw.hhh));
songslist.add(new Songs("hhhhh", "cHU CHU ", R.drawable.abby, R.raw.hhh));
final SongsAdapter adapter = new SongsAdapter(this, songslist);
final ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Songs song = songslist.get(position);
Intent anotherActivityIntent = new Intent(FunActivity.this, playingActivity.class);
anotherActivityIntent.putExtra("songs",songslist);
startActivity(anotherActivityIntent);
}
});
比赛活动:
public class playingActivity extends FunActivity {
private MediaPlayer mMediaPlayer;
private Button buttonPlayStop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
ArrayList<Songs> songs = getIntent().getParcelableArrayListExtra("Songs");
buttonPlayStop = (Button)findViewById(R.id.ButtonPlayStop);
buttonPlayStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mMediaPlayer.start();
}
});
}
未经测试但..
第一项活动:
更改
anotherActivityIntent.putExtra("songs",songslist);
至
anotherActivityIntent.putExtra("songs",song);
比赛活动:
更改
ArrayList<Songs> songs = getIntent().getParcelableArrayListExtra("Songs");
至
Songs songs = getIntent().getParcelableExtra("songs");
你需要在Play活动中添加一些代码
- 将歌曲翻译成它的路径(也许最好在Songs类中拥有路径)
- 设置mMediaPlayer的路径(请参阅MediaPlayer.setDataSource(string))
- 致电mMediaPlayer.prepare()
- 然后打电话给mMediaPlayer.start()
注意:在你的代码中设置为buttonPlayStop的onClickListener.mMediaPlayer.start()
中调用onClick()
似乎是一个错字。
有关更多信息,请参阅MediaPlayer.StateDiagram或MediaPlayer developer guide。
试着改变
anotherActivityIntent.putExtra("songs",songslist);
至
anotherActivityIntent.putParcelableArrayListExtra("songs",songslist);
同时更改你使用错误的密钥名称songs
和Songs
为双方做同样的事情
ArrayList<Songs> songs = getIntent().getParcelableArrayListExtra("songs");
您还需要在onclick之前投射媒体播放器对象,如下所示
mMediaPlayer = (MediaPlayer)findViewById(You media player id);