如何检索最新播放的歌曲?

时间:2017-11-19 06:08:36

标签: android arraylist android-recyclerview android-mediaplayer android-music-player

我正在创建一个最近播放过歌曲的音乐播放器播放列表。我正在存储歌曲的arraylist和正在共享偏好中播放的歌曲的索引。我正在做的是获取最近播放的歌曲,从共享首选项中检索arraylist和歌曲索引,并将其保存在另一个arraylist中。但问题是recyclerView一次只能显示一首歌。

例如,如果我播放了歌曲A,则recyclerView应该在第一个位置显示歌曲A,然后如果我播放歌曲B,则recyclerView应该在第一个位置显示歌曲B,在第二个位置显示歌曲A.但它只显示了第一个位置。

RecentlyPLayedsongs.java

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LayoutInflater inflater = LayoutInflater.from(this);
    View view6 = inflater.inflate(R.layout.activity_recently_played, null);
    FrameLayout container6 = (FrameLayout) findViewById(R.id.container);
    container6.addView(view6);

    recyclerView_recently_played = findViewById(R.id.recyclerView_recently_played);

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView_recently_played.setLayoutManager(linearLayoutManager);

    StorageUtil storageUtil2 = new StorageUtil(getApplicationContext());

    SongList=storageUtil2.loadAudio();

    pos = storageUtil2.loadAudioIndex();

    songInfoModel = SongList.get(pos);

    RecentlyPlayedList.add(songInfoModel);

    adapter1 = new Playlist_Recently_Added_Adapter(RecentlyPlayedList, getApplicationContext());
    recyclerView_recently_played.setAdapter(adapter1);

}

1 个答案:

答案 0 :(得分:0)

您可以通过以下两种方式之一来实现此目的

  1. 在通过歌曲列表之前,您需要根据时间进行排序。在这种情况下,你还需要节省播放歌曲的时间。(好吧,要实现这一点,你需要做很多编码和维护)
  2. 这是更简单的方法。你可以使用数组列表的 add()方法,你可以在那里指定位置以及下面的代码中提到的

    list.add(o,currentSong);

  3. 这里传递0意味着每当你正在播放一首将在0索引处添加的歌曲时,这意味着你最新播放的歌曲将始终位于顶部。 希望对你有帮助。

    注意:我已经验证了第二个解决方案,下面的代码可以按预期工作

    List<Integer> list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
    
        Log.d(TAG, "firs time");
        for (int a=0; a < list.size();a++ ) {
            Log.d(TAG, "" + list.get(a));
        }
    
        list.add(0,4);
    
        Log.d(TAG, "second time");
        for (int a=0; a < list.size();a++ ) {
            Log.d(TAG, "" + list.get(a));
        }
    

    日志如下所述

    11-19 11:24:53.400 3681-3681/com.example.awaheed.datetime D/test: firs time
    11-19 11:24:53.400 3681-3681/com.example.awaheed.datetime D/test: 1
    11-19 11:24:53.400 3681-3681/com.example.awaheed.datetime D/test: 2
    11-19 11:24:53.400 3681-3681/com.example.awaheed.datetime D/test: 3
    11-19 11:24:53.400 3681-3681/com.example.awaheed.datetime D/test: second time
    11-19 11:24:53.400 3681-3681/com.example.awaheed.datetime D/test: 4
    11-19 11:24:53.400 3681-3681/com.example.awaheed.datetime D/test: 1
    11-19 11:24:53.400 3681-3681/com.example.awaheed.datetime D/test: 2
    11-19 11:24:53.400 3681-3681/com.example.awaheed.datetime D/test: 3
    

    看看第二次加入的日志号码&#39; 0&#39;索引,而不是在第一个位置,并且转储项目被推下。希望这是有道理的。

相关问题