我有两个活动Play.java和Home.java,Home.java包含Listview的onclick函数并获取listview的位置 我需要将该位置传递给Play.java.when我点击listview"不幸的是应用已关闭"
Home.java
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
{
int songindex = position;
Intent intent = new Intent(this, Play.class);
startActivity(intent);
p1.listen(songindex);
}
Play.java
public void change(View v)
{
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}
public void listen(int songindex)
{
MediaPlayer mPlayer2;
if(songindex==0)
{
mp=MediaPlayer.create(this, R.raw.gayatri);
mp.start();
}
else if(songindex==1)
{
mPlayer2= MediaPlayer.create(this, R.raw.brahma);
mPlayer2.start();
}
}
当我点击列表视图中的歌曲时,它的工作应用已关闭
答案 0 :(得分:0)
你必须使用意图传递位置。
Home.java
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
{
int songindex = position;
Intent intent = new Intent(this, Play.class);
intnt.putExtra("position",position);
startActivity(intent);
// p1.listen(songindex);
}
Play.java
public void change(View v)
{
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}
public void listen(int songindex)
{
Bundle data = getIntent().getExtras();
int position = data.getInt("position");
MediaPlayer mPlayer2;
if(songindex==0)
{
mp=MediaPlayer.create(this, R.raw.gayatri);
mp.start();
}
else if(songindex==1)
{
mPlayer2= MediaPlayer.create(this, R.raw.brahma);
mPlayer2.start();
}
}
答案 1 :(得分:0)
将listen功能放在主文件中
Home.java
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
{
listen(position);
}
public void listen(int songindex)
{
MediaPlayer mPlayer2;
if(songindex==0)
{
mp=MediaPlayer.create(this, R.raw.gayatri);
mp.start();
}
else if(songindex==1)
{
mPlayer2= MediaPlayer.create(this, R.raw.brahma);
mPlayer2.start();
}
}
答案 2 :(得分:0)
LogCat应该为你带来问题,但我们仍然没有。
那为什么你需要mp和mp2?一次播放两首歌?
我只有一个mp,在课堂上声明,而不是在方法中,因为在你的情况下,对于mp2播放器的参考在退出listen方法后会丢失,并且无法控制它(事实上,退出方法后它甚至可能会停止播放。)
简而言之,这就是我的建议:
MediaPlayer mp;
static final int table[] songIndexIds= { R.raw.song1, R.raw.song2};
public void listen(int songIndex)
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
if (songIndex >= 0) {
mp=MediaPlayer.create(this, songIndexIds[songIndex]);
mp.start();
}
}
// "Destructor"
@Override
public void finalize() {
if (mp != null) {
mp.stop();
mp.release();
}
}