猿问

无法在屏幕旋转时保持 RecyclerView 位置

我正在加载一个RecyclerView基于调用Retrofit和存储在本地SQLite数据库中的数据。


在屏幕旋转时,RecyclerView保持重置。此外,当我收藏一部电影(将电影添加到我的本地房间数据库)时,在某些情况下,我的微调器与要填充到RecyclerView. 下面是我的代码:


public class MainActivity extends AppCompatActivity {


private RecyclerView mMovieResults;

private MyAdapter mMovieResultsAdapter;

private String query;

private String mBaseURL;

private int lastFirstVisiblePosition;

//TODO: How is someone able to load my API Key if I am storing it



private ArrayList<String> mMovieURLS;

private ArrayList<Movie> mMovies;

private List<Movie> mMovieResultsList;


private static final String SPINNER_SELECTION = "SPINNER_SELECTION";


private boolean mIsFavoriteSelected;


private AppDatabase mDb;


private Spinner mSpinner;


private SharedPreferences mPrefs;

private SharedPreferences.Editor mPrefsEditor;


private static Bundle mBundleRecyclerViewState;



private int saved_selection = -1;



@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    Log.v("ONCREATE", "ONCREATE");

    if (savedInstanceState != null){

        saved_selection = savedInstanceState.getInt(SPINNER_SELECTION);

    }


    if (isOnline()) {

        setContentView(R.layout.activity_main);

        Stetho.initializeWithDefaults(this);

        mDb = AppDatabase.getInstance(getApplicationContext());

        mMovieResults = findViewById(R.id.main_recyclerview_image_results);

        GridLayoutManager glm = new GridLayoutManager(this, 3);

        glm.setOrientation(LinearLayoutManager.VERTICAL);

        mMovieResults.setLayoutManager(glm);

        mMovieURLS = new ArrayList<>();

        mMovies = new ArrayList<>();

        mMovieResultsList = new ArrayList<>();

        mMovieResultsAdapter = new MyAdapter(mMovieResultsList);

        mMovieResults.setAdapter(mMovieResultsAdapter);

        mDb = AppDatabase.getInstance(getApplicationContext());

        mPrefs = getSharedPreferences("prefs", MODE_PRIVATE);


HUX布斯
浏览 253回答 2
2回答

慕尼黑的夜晚无繁华

RecyclerView 只保存其滚动位置,直到您调用setAdapter.&nbsp;通过setAdapter在您仍然没有数据时调用,滚动位置将被丢弃(如果没有位置 4,则无法滚动到位置 4)。您应该等到有数据才能调用setAdapter.

墨色风雨

当您旋转设备时,android 会检测配置更改并默认重新启动 Activity。通过这种方式,您的活动再次调用适配器,您的 recyclerview 返回到零位置。通过添加下面的命令,您的意思是您自己处理此配置更改,因此 android 不会重新启动您的活动。将此行添加到清单文件中的活动标记android:configChanges="screenSize|orientation"像这样:&nbsp; &nbsp; <activity&nbsp; &nbsp; &nbsp; &nbsp; android:name=".SearchActivity"&nbsp; &nbsp; &nbsp; &nbsp; android:configChanges="screenSize|orientation"&nbsp; &nbsp; &nbsp; &nbsp; android:label="@string/search"&nbsp; &nbsp; &nbsp; &nbsp; android:theme="@style/AppTheme.NoActionBar">&nbsp; &nbsp; &nbsp; &nbsp; <intent-filter>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <action android:name="android.intent.action.MAIN" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <category android:name="android.intent.category.DEFAULT" />&nbsp; &nbsp; &nbsp; &nbsp; </intent-filter>&nbsp; &nbsp; </activity>
随时随地看视频慕课网APP

相关分类

Java
我要回答