Android MVVM 实时数据方向更改

问题描述 投票:0回答:1

我是 Android 开发新手。 当屏幕方向改变时尝试保留状态。 我有一个带有字段 url 的歌曲模型。我想播放 url 中的 mp3 文件。 播放正常,但当屏幕方向改变时会重新开始。

不知道Live Data是否适合解决这个问题。

public class MainActivity extends AppCompatActivity {

    private SongViewModel songViewModel;
    
    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_song_item);

        //define viewmodel
        songViewModel = new ViewModelProvider(this).get(SongViewModel.class);
        // get song through viewModel
        songViewModel.getLiveSongData().observe(this, songList -> {
            String url = songList.get(0).getUrl();
            ArgAudio audio = ArgAudio.createFromURL("test", "test", url);
            ArgPlayerSmallView argMusicPlayer = (ArgPlayerSmallView) findViewById(R.id.argmusicplayer);
            argMusicPlayer.play(audio);

        });


    }

}
public class SongRepository
{
    MutableLiveData<List<Song>> songListMutableLiveData;
    FirebaseFirestore mFirestore;
    MutableLiveData<Song> songMutableLiveData;

    public SongRepository() {
        this.songListMutableLiveData = new MutableLiveData<>();
        //define firestore
        mFirestore = FirebaseFirestore.getInstance();
        //define songlist
        songMutableLiveData = new MutableLiveData<>();

    }


    //get song from firebase firestore
    public MutableLiveData<List<Song>> getSongListMutableLiveData() {
        Log.i("TAG", "getSongListMutableLiveData: ");

        mFirestore.collectionGroup("songs").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                List<Song> songList = new ArrayList<>();
                for (QueryDocumentSnapshot doc : value) {
                    if (doc != null) {
                        songList.add(doc.toObject(Song.class));
                    }
                }
                songListMutableLiveData.postValue(songList);
            }
        });
        return songListMutableLiveData;
    }

}
public class SongViewModel extends ViewModel {
    MutableLiveData<List<Song>> songListMutableLiveData;
    FirebaseFirestore mFirestore;
    SongRepository songRepository;


    public SongViewModel() {
        songRepository = new SongRepository();
        mFirestore = FirebaseFirestore.getInstance();
                songListMutableLiveData = songRepository.getSongListMutableLiveData();



    }
    public MutableLiveData<List<Song>> getLiveSongData()
    {
        return songListMutableLiveData;
    }

}
android android-livedata
1个回答
0
投票

要在屏幕方向改变时保留状态,可以使用 LiveData 和 ViewModel 的组合。

LiveData 就适合这个问题,它可以让你观察数据的变化,并在数据变化时自动更新 UI 组件。 ViewModel 将在配置更改(例如屏幕方向更改)中幸存。

以下是如何修改代码以在屏幕方向变化时保留歌曲及其状态:

创建一个 ViewModel 来保存当前播放的歌曲及其状态。

public class SongViewModel extends ViewModel {
    private MutableLiveData<Song> currentSongLiveData = new MutableLiveData<>();

    public LiveData<Song> getCurrentSongLiveData() {
        return currentSongLiveData;
    }

    public void setCurrentSong(Song song) {
        currentSongLiveData.setValue(song);
    }
}

在 MainActivity 中,使用 ViewModel 保留当前播放的歌曲及其状态。

public class MainActivity extends AppCompatActivity {
    
        private SongViewModel songViewModel;
        private ArgPlayerSmallView argMusicPlayer;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.single_song_item);
    
            // Initialize the ViewModel
            songViewModel = new ViewModelProvider(this).get(SongViewModel.class);
    
            // Initialize your ArgPlayerSmallView
            argMusicPlayer = findViewById(R.id.argmusicplayer);
    
            // Observe changes to the current song
            songViewModel.getCurrentSongLiveData().observe(this, song -> {
                if (song != null) {
                    String url = song.getUrl();
                    ArgAudio audio = ArgAudio.createFromURL("test", "test", url);
                    argMusicPlayer.play(audio);
                }
            });
    
            // Load and set the initial song (you can change this part according to your logic)
            List<Song> songList = songViewModel.getLiveSongData().getValue();
            if (songList != null && !songList.isEmpty()) {
                songViewModel.setCurrentSong(songList.get(0));
            }
        }
    }

更新您的 ViewModel 以提供设置当前歌曲的方法。

当你想改变当前播放的歌曲时,使用ViewModel设置新歌曲。

// Example of changing the currently playing song
Song newSong = /* get the new song */;
songViewModel.setCurrentSong(newSong);

通过使用 LiveData 和 ViewModel,您可以确保当前播放的歌曲在屏幕方向变化时保留,并且您的音乐播放器状态保持不变。

© www.soinside.com 2019 - 2024. All rights reserved.