ListView OnItemClickListener 歌曲

我创建了一个 ListView (myList)。通过按下 ListView 上的其中一项,应用程序应该将用户定向到 PlaySongActivity 页面。我使用了 searchById 函数来尝试匹配歌曲的 ID 和我数据库中的歌曲。(获取歌曲的 ID 并匹配数据库中的歌曲 ID 以播放同一首歌曲)但是,我的老师告诉我我正在搜索ListView 的 ID,而不是歌曲。


那么有什么方法可以按歌曲名称搜索或可能为 ListView 中的每个项目添加一个 ID?


我是编码的初学者,已经搜索了几个小时,但在互联网上找不到解决方案:(


private SongCollection mySongCollection = new SongCollection();


myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                Intent intent = new Intent(SearchSong.this, PlaySongActivity.class);


                String resourceId = AppUtil.getResourceId(SearchSong.this, myList);

                Song selectedSong = mySongCollection.searchById(resourceId);

                AppUtil.popMessage(SearchSong.this, "Streaming music: " + selectedSong.getTitle());


                intent.putExtra("id", selectedSong.getId());

                intent.putExtra("title", selectedSong.getTitle());

                intent.putExtra("artiste", selectedSong.getArtiste());

                intent.putExtra("fileLink", selectedSong.getFileLink());

                intent.putExtra("coverArt", selectedSong.getCoverArt());


                startActivity(intent);

            }

        });

SongCollection.class代码



    package com.example.musix;


public class SongCollection {

    private Song[] allSongs = new Song[9];

    public SongCollection (){

        prepareSongs();

    }

慕神8447489
浏览 257回答 1
1回答

慕森卡

String resourceId = AppUtil.getResourceId(SearchSong.this, myList);&nbsp;Song selectedSong = mySongCollection.searchById(resourceId);resourceId 将成为列表视图元素的 id(例如,第一个元素 id = 0、第二个 id = 1 等等)。public Song searchById (String id){&nbsp; &nbsp; &nbsp; &nbsp; Song selectedSong = null;&nbsp; &nbsp; &nbsp; &nbsp; for(int index=0; index<allSongs.length; index++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectedSong = allSongs[index];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(selectedSong.getId().equals(id)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return selectedSong;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return selectedSong;}应该:public Song searchById (String id){&nbsp; &nbsp; &nbsp; &nbsp; //we are returning the song selected by the index of its Arrays&nbsp; &nbsp; &nbsp; &nbsp; Song selectedSong = allSongs[Integer.parseInt(id)];&nbsp; &nbsp; return selectedSong;}为什么?:您返回实际的 songid,但在&nbsp;Song selectedSong = mySongCollection.searchById(resourceId); <-- resourceId is already the Id stored in the database and not the index of mySongCollection.&nbsp;intent.putExtra("id", selectedSong.getId());您已经在使用实际歌曲 ID。这没有意义,因为您已经可以识别出实际的歌曲。因此,要么应用这些更改,要么更改此行:intent.putExtra("id", resourceId);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java