无论我选择遵循stackoverflow中的哪个示例,我都无法获得所需的结果。
我想在旋转时保存recyclelerView滚动位置,但选择(TOP RATED MOVIES, FAVORITE MOVIES AND POPULAR MOVIES )
状态的保存似乎覆盖了重新加载所需选择的状态,但是从屏幕顶部开始。
E.g。在它的底部的一半或全部,然后,旋转它保存选择类型(例如它在旋转前显示的任何内容)但是从头开始加载(顶部(这是不希望的,我需要留在相同的位置))。
我的代码:
MainActivity
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
public static final int POP = 1;
public static final int TOP = 2;
public static final int FAV = 3;
int selection = -1;
private RecyclerView rv;
private MovieAdapter adapter;
private MovieDbHelper dbHelper;
private FrameLayout frame;
private AppCompatActivity activity = MainActivity.this;
private static final String BUNDLE_RECYCLER_LAYOUT = "classname.recycler.layout";
public static int index = -1;
public static int top = -1;
int currentVisiblePosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!isOnline()) {
Toast.makeText(activity, "No Connection", Toast.LENGTH_SHORT).show();
} else {
initControls();
dbHelper = new MovieDbHelper(activity);
if (savedInstanceState != null) {
selection = savedInstanceState.getInt("selection");
//Now just load the list
switch (selection) {
case POP:
loadJSON(POP);
break;
case TOP:
loadJSON(TOP);
break;
case FAV:
initializeFavorites();
break;
case -1:
initializeViews();
break;
}
} else {
initializeViews();
}
}
}
private void initControls() {
rv = findViewById(R.id.rv_main);
adapter = new MovieAdapter(this, new ArrayList<Movie>());
rv.setLayoutManager(new GridLayoutManager(this, ScreenSizeUtil.calculateNoOfColumns(this)));
rv.setItemAnimator(new DefaultItemAnimator());
rv.setAdapter(adapter);
dbHelper = new MovieDbHelper(activity);
frame = findViewById(R.id.frame);
checkSortOrder();
}
private void initializeViews() {
Toast.makeText(this, "Change sort order via the Settings Menu....", Toast.LENGTH_SHORT).show();
}
private void initializeFavorites() {
getAllFavorites();
}
private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
private void loadJSON(int listType) {
try {
if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
Toast.makeText(this, "Error with Api Key....", Toast.LENGTH_SHORT).show();
return;
}
Client Client = new Client();
Service apiService =
Client.getClient().create(Service.class);
Call<MovieResponse> call = listType==TOP? apiService
.getMovies("top_rated",BuildConfig.THE_MOVIE_DB_API_TOKEN): apiService.getMovies("popular",BuildConfig.THE_MOVIE_DB_API_TOKEN) ;
call.enqueue(new Callback<MovieResponse>() {
@Override
public void onResponse(Call<MovieResponse> call, final Response<MovieResponse> response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
List<Movie> movies = response.body().getResults();
adapter.setMovieList(movies);
rv.scrollToPosition(0);
}
});
}
@Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
Toast.makeText(MainActivity.this, "Error with Data!", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Log.d("Error", e.getMessage());
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(BUNDLE_RECYCLER_LAYOUT, rv.getLayoutManager().onSaveInstanceState());
}
private void checkSortOrder(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String sortOrder = preferences.getString(
this.getString(R.string.pref_sort_order_key),
this.getString(R.string.pref_most_popular)
);
if (sortOrder.equals(this.getString(R.string.pref_most_popular))) {
Log.d(TAG, "Sorting by most popular");
loadJSON(POP);
} else if (sortOrder.equals(this.getString(R.string.pref_highest_rated))){
Log.d(TAG, "Sorting by Top rated");
loadJSON(TOP);
} else{
Log.d(TAG, "Sorting by Favorites");
initializeFavorites();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
(rv.getLayoutManager()).scrollToPosition(currentVisiblePosition);
currentVisiblePosition = 0;
}
@Override
public void onPause() {
super.onPause();
currentVisiblePosition = 0;
currentVisiblePosition = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();}
private void getAllFavorites() {
new AsyncTask<Void, Void, ArrayList<Movie>>() {
@Override
protected ArrayList<Movie> doInBackground(Void... voids) {
return new ArrayList<>(dbHelper.getAllFavorites());
}
@Override
protected void onPostExecute(ArrayList<Movie> aVoid) {
super.onPostExecute(aVoid);
adapter.setMovieList(aVoid);
}
}.execute();
}
}
任何建议都会很棒,请注意与How to save scroll position of RecyclerView in Android?的细微差别。
由于 本