gpt4 book ai didi

java - 在加载了 LiveDate 对象的 fragment 中旋转屏幕后如何保持 ScrollView 中的滚动位置

转载 作者:行者123 更新时间:2023-12-02 02:13:36 27 4
gpt4 key购买 nike

我有一个 fragment ,用于显示歌曲的歌词,该歌词是根据给定的 id 从房间数据库加载的。

我想在旋转屏幕后保留滚动位置。现在,旋转后,歌曲会再次从数据库加载,并且无论旋转之前的滚动位置如何, View 都位于最顶部。

我认为我可以在onSaveInstanceState中保存滚动位置,在onCreateView()中使用命令mSongDisplayScrollView.scrollTo(x, y) >

fragment 代码:


public class SongDisplayFragment extends Fragment {

private Song mSongToDisplay;

private ScrollView mSongDisplayScrollView;
private TextView mSongTitleTextView;
private RecyclerView mSongLyricsRecyclerView;

private GuitarSongbookViewModel mGuitarSongbookViewModel;

public static final String SONG_ID_KEY = "SONG_ID_KEY";


public SongDisplayFragment() {

}

public static SongDisplayFragment newInstance(Long songId) {
SongDisplayFragment songDisplayFragment = new SongDisplayFragment();
Bundle arguments = new Bundle();
arguments.putLong(SONG_ID_KEY,
songDisplayFragment.setArguments(arguments);
return songDisplayFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_song_display, container, false);

mSongDisplayScrollView = view.findViewById(R.id.song_display_scroll_view);
mSongLyricsRecyclerView = view.findViewById(R.id.lyrics_rv_);
mSongTitleTextView = view.findViewById(R.id.

mGuitarSongbookViewModel = ViewModelProviders.of(this).get(GuitarSongbookViewModel.class);

final SongDisplayAdapter songDisplayAdapter = new SongDisplayAdapter(getContext());

Long songId = null;
if (getArguments().containsKey(SONG_ID_KEY)) {
songId = getArguments().getLong(SONG_ID_KEY);
}

if (songId != null) {
final Long finalSongId = songId;


mGuitarSongbookViewModel.getSongById(songId).observe(this, new Observer<Song>() {
@Override
public void onChanged(@Nullable final Song song) {
mSongToDisplay = song;
mSongTitleTextView.setText(mSongToDisplay.getMTitle());
songDisplayAdapter.setSong(song);

}
});


}


mSongLyricsRecyclerView.setAdapter(songDisplayAdapter);
mSongLyricsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

return view;
}

}

fragment XML:


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.SongDisplayFragment">

<ScrollView
android:id="@+id/song_display_scroll_view"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/autoscroll_bar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:layout_editor_absoluteX="138dp">

<LinearLayout

android:id="@+id/son_display_linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
android:id="@+id/displayed_song_title_txt_"
style="@style/TitleOfDisplayedSong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:text="@string/title_placeholder" />

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/lyrics_rv_"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
android:layout_marginBottom="12dp"
android:nestedScrollingEnabled="false" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

该 fragment 在 textView 和 RecyclerView 中显示歌曲的标题和歌词,适配器类代码为:

package com.example.guitarsongbook.adapters;

import android.content.Context;
import android.graphics.Rect;
import android.text.Html;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.guitarsongbook.R;
import com.example.guitarsongbook.daos.SongChordJoinDao;
import com.example.guitarsongbook.model.Chord;
import com.example.guitarsongbook.model.Song;

import java.util.ArrayList;
import java.util.List;


public class SongDisplayAdapter extends RecyclerView.Adapter<SongDisplayAdapter.SongViewHolder> {

private Context context;
private final LayoutInflater mInflater;

private Song mSong;
private ArrayList<String> mLyrics;

public SongDisplayAdapter(Context context) {
this.context = context;
mInflater = LayoutInflater.from(context);
}

@NonNull
@Override
public SongViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.song_lyrics_rv_item, parent, false);
return new SongDisplayAdapter.SongViewHolder(itemView);
}

public void setSong(Song song){
mSong = song;
mLyrics = mSong.getMLyrics();
notifyDataSetChanged();
}



@Override
public void onBindViewHolder(@NonNull SongViewHolder holder, int position) {
holder.bindTo(position);
}

@Override
public int getItemCount() {
if (mLyrics != null)
return mLyrics.size();
else return 0;
}

public class SongViewHolder extends RecyclerView.ViewHolder {

private final TextView mLyricsLineTextView;


public SongViewHolder(@NonNull View itemView) {
super(itemView);
mLyricsLineTextView = itemView.findViewById(R.id.song_lyric_line_txt_);
}

public void bindTo(int position) {
if (mSong != null) {
mLyricsLineTextView.setText(Html.fromHtml(mLyrics.get(position)));



} else {
mLyricsLineTextView.setText(context.getString(R.string.no_song_label));
}
}
}


}

RecyclerView 项目 XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
android:id="@+id/song_lyric_line_txt_"
style="@style/LyricOfDisplayedSong"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="24dp"
app:layout_constraintEnd_toStartOf="@+id/song_chord_line_txt_"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="placeholder text" />


</androidx.constraintlayout.widget.ConstraintLayout>

我认为问题在于,旋转屏幕后,必须通过观察者的方法 onChange() 再次加载歌曲,因此有一小会儿,scrollView 没有任何内容可显示。我想找到一些解决方案,如何在再次加载歌曲后返回到旧位置。

最佳答案

第一步是通过 Fragment 的 onSaveInstanceState 方法保存对象的值。

我的更多解释将来自每个代码块中的注释,因此您可以更好地理解它是如何工作的。

Values to be persisted: mSongToDisplay and mScrollViewPosition

//new variable introduced
int mScrollViewPosition = 0;

@Override
protected void onSaveInstanceState(Bundle outState) {
//If screen orientation changes, android redraws all views
//and non persistent data would be lost.
//Nevertheless, before this happens android informs the app via this method
//So to prevent state loss we save the data to a temporary storage
outState.putParcelable("song_data", mSongToDisplay);
//save ScrollView current position
outState.putInt("position_data", mSongDisplayScrollView.getScrollY());
//call super to commit your changes
super.onSaveInstanceState(outState);
}

接下来是方向改变完成后恢复数据

fragments onCreateView 中添加以下 block ,并确保 if 语句 block 在初始化适配器之后出现

 ...
//...add adapter initialization block here before checking for saved data

//Check for saved data
if (savedInstanceState != null) {
// Retrieve the data you saved
mSongToDisplay = savedInstanceState.getParcelable("song_data");
mScrollViewPosition = savedInstanceState.getInt("position_data");

//Re-initialize and reload adapter record
mSongToDisplay = song;
mSongTitleTextView.setText(mSongToDisplay.getMTitle());
songDisplayAdapter.setSong(song);
}
else {
//No data to retrieve
//initialize data model here.
}

//Assign the adapter to recyclerView
mSongLyricsRecyclerView.setAdapter(songDisplayAdapter);
mSongLyricsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
try{
//Finally we set the scrollview position at this point just to make sure
//recyclerview has its data loaded and full length of scrollview is restored
mSongDisplayScrollView.setScrollY(mScrollViewPosition);}
catch(Exception ex){
//position isn't right
}
return view;

此时所需的数据已被保留,并且在每个 screenOrientationChange 上,应用程序会将之前保存的歌曲对象加载到适配器中,以防止错误调用db 或 api >,并且还会使用保存的整数值mScrollViewPosition滚动到预期位置。

关于java - 在加载了 LiveDate 对象的 fragment 中旋转屏幕后如何保持 ScrollView 中的滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57315938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com