如果这是一个重复,我道歉,但是我的研究在找到与这个具体案例相关的内容时是空洞的。
我正在尝试创建一个应用程序,其中用户单击活动中的按钮,并在另一个以歌曲标题作为内容的活动中使用listView提示。当用户单击listView项时,将播放相应的歌曲(保存在Raw文件中)。假设现在歌曲被命名为song1,song2等。我有应用程序努力选择这首歌。它们会被列表视图提示,它会正确显示标题,但是从这一点来看,我仍然不知道该怎么做。
基本上,我需要帮助处理用户点击任何给定项目以在原始活动中播放该歌曲。
主要活动代码:
public class HomeScreen extends Activity {
//set view to the home screen
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
}
//Show the Activity for the song list
public void showSongList (View clickedButton) {
// the showSongList is defined in the layout xml file.
Intent switchScreen = new Intent(HomeScreen.this, SongList.class);
startActivity(switchScreen);
}
}
使用listView的活动代码
public class SongList extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Store the string resources into the array
String[] music_list = getResources().getStringArray(R.array.songs);
//Binding resources array into adapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, music_list));
}
}
这是字符串数组的XML,列表基于
<resources>
<string-array name="songs">
<!-- Go back will be defined later to return to the original Activity -->
<item>Go Back</item>
<item>First Song</item>
<item>Second Song</item>
<item>Third Song</item>
<item>Fourth Song</item>
<item>Fifth Song</item>
<item>Sixth Song</item>
<item>Seventh Song</item>
<item>Eighth Song</item>
<item>Ninth Song</item>
<item>Tenth Song</item>
<item>Eleventh Song</item>
<item>Twelfth Song</item>
</string-array>
</resources>
我很抱歉,对于知道自己在做什么的人来说,这可能是一个简单的问题。
如果需要发布任何额外的代码,请询问。提前致谢。
答案 0 :(得分:0)
您可以将setonitemClickListener
添加到列表视图中。 在听众中,您将在列表视图中获得歌曲的位置。因此您可以知道用户选择的歌曲并播放音乐。
至于播放音乐的代码,我是对不起,我没用过。
顺便说一下,如果你需要添加或删除歌曲,按文件列出歌曲可能会更好。
mListView.setOnItemClickListener(new OnItemClickListener(){
@覆盖
public void onItemClick(AdapterView arg0,View arg1,int arg2,long arg3){
// arg2表示选择的歌曲posision。您可以使用参数
}来控制您的游戏 });
在您的代码中, mListView 此。
答案 1 :(得分:0)
要完成此任务,请使用onItemClickListener。在列表视图上设置它并使用onItemClick()中的position参数来获取每个项目的位置。然后将其传递给任何解决位置并通过创建其对象来播放歌曲的方法。
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
i = arg2;
musicPlay(b1);
}
public void musicPlay(View v){
int id=0;
if(i==0){
id=R.raw.abc;
}
if(i==1){
id=R.raw.abcde;
}
if(i==2){
id=R.raw.gghi;
}
if(mp==null){
mp=MediaPlayer.create(this, id);
mp.start();
}
mp=MediaPlayer.create(this, id);
mp.start();
}
这里使用i作为全局整数变量。 希望这会有所帮助。