在屏幕旋转后,Recyclerview不会滚动到保存位置

时间:2017-12-08 19:08:29

标签: java android android-layout android-recyclerview gridlayoutmanager

您好我想在屏幕旋转时保存Recylerview滚动位置,以便Recyclerview在用户看到屏幕之前滚动到该位置。 到目前为止,我已经尝试了所有可能的解决方案来解决类似的问我正在使用带有Recyclerview的GridLayoutManager并使用JSON数据显示电影的网格列表。

请看看!!

MainActivity:

public class MainActivity extends AppCompatActivity implements 
SharedPreferences.OnSharedPreferenceChangeListener {

private RecyclerView recyclerView;

private ArrayList<Movie> movieList;

MovieAdapter adapter;
private final String KEY_RECYCLER_STATE = "recycler_state";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    movieList = new ArrayList<>();
    adapter = new MovieAdapter(this, movieList);
    /*
    if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    } else {
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
    }
    */
    recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    recyclerView.setAdapter(adapter);

    checkSort();

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putParcelable(KEY_RECYCLER_STATE, recyclerView.getLayoutManager().onSaveInstanceState());
}

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

    if(savedInstanceState != null)
    {
        Parcelable savedRecyclerLayoutState = savedInstanceState.getParcelable(KEY_RECYCLER_STATE);
        recyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerLayoutState);
    }
}

public Activity getActivity() {
    Context context = this;
    while (context instanceof ContextWrapper) {
        if (context instanceof Activity) {
            return (Activity) context;
        }
        context = ((ContextWrapper) context).getBaseContext();
    }
    return null;

}

private void JSONMostPopularMovie() {
    try {
        if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
            Toast.makeText(getApplicationContext(), "There Is No API Key!", Toast.LENGTH_SHORT).show();
            return;
        }

        MovieApi movieapi = new MovieApi();
        MovieService apiService = MovieApi.getClient().create(MovieService.class);
        Call<MovieResponse> call = apiService.getPopularMovies(BuildConfig.THE_MOVIE_DB_API_TOKEN);
        call.enqueue(new Callback<MovieResponse>() {

            @Override
            public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
                ArrayList<Movie> movies = response.body().getResults();
                adapter.setMovies(movies);
                Toast.makeText(MainActivity.this, "Displaying By Most Popular Movies", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFailure(Call<MovieResponse> call, Throwable t) {
                Log.d("Error", "" + t.getMessage());
                Toast.makeText(MainActivity.this, "Error Fetching Data! And Internet Connection", Toast.LENGTH_SHORT).show();

            }


        });

    } catch (Exception e) {
        Log.d("Error", e.getMessage());
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }

}

private void JSONTopRateMovie() {
    try {
        if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
            Toast.makeText(getApplicationContext(), "There Is No API Key", Toast.LENGTH_SHORT).show();
            return;
        }

        MovieApi movieapi = new MovieApi();
        MovieService apiService = MovieApi.getClient().create(MovieService.class);
        Call<MovieResponse> call = apiService.getTopRatedMovies(BuildConfig.THE_MOVIE_DB_API_TOKEN);
        call.enqueue(new Callback<MovieResponse>() {

            @Override
            public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
                ArrayList<Movie> movies = response.body().getResults();
                adapter.setMovies(movies);
                Toast.makeText(MainActivity.this, "Displaying By Top Rated Movies", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<MovieResponse> call, Throwable t) {
                Log.d("Error", "" + t.getMessage());
                Toast.makeText(MainActivity.this, "Error Fetching Data! And Internet Connection", Toast.LENGTH_SHORT).show();

            }
        });
    } catch (Exception e) {
        Log.d("Error", e.getMessage());
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_settings:
            Intent setting = new Intent(this, MovieSettings.class);
            startActivity(setting);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    checkSort();
}

private void checkSort() {
    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(LOG_TAG, "Sorting by most popular");
        JSONMostPopularMovie();
    } else if (sortOrder.equals(this.getString(R.string.top_rated))) {
        Log.d(LOG_TAG, "Sorting by top rated");
        JSONTopRateMovie();
    } 
}
}

适配器:

public class MovieAdapter extends 
RecyclerView.Adapter<MovieAdapter.MyViewHolder> {

private Context mContext;
private ArrayList<Movie> movieList;

public MovieAdapter(Context mContext, ArrayList<Movie> movieList) {
    this.mContext = mContext;
    this.movieList = movieList;
}

@Override
public MovieAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.movie_item, viewGroup, false);

    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(final MovieAdapter.MyViewHolder viewHolder, int i) {
    viewHolder.title.setText(movieList.get(i).getOriginalTitle());
    String vote = Double.toString(movieList.get(i).getVoteAverage());
    viewHolder.userrating.setText(vote);

    String poster = "https://image.tmdb.org/t/p/w185/" + movieList.get(i).getPosterPath();
    Picasso.with(mContext)
            .load(poster)
            .into(viewHolder.thumbnail);

}

@Override
public int getItemCount() {
    return movieList.size();
}

public void setMovies(ArrayList<Movie> movies){
    this.movieList = movies;
    notifyDataSetChanged();
}


public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title, userrating;
    public ImageView thumbnail;

    public MyViewHolder(final View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.title);
        userrating = (TextView) view.findViewById(R.id.userrating);
        thumbnail = (ImageView) view.findViewById(R.id.thumbnail);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    Intent intent = new Intent(mContext, MovieDetail.class);
                    intent.putExtra("movie", movieList.get(position));
                    intent.putExtra("id", movieList.get(position).getId());
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);

                }
            }
        });
    }
}
}

0 个答案:

没有答案