在屏幕旋转时保持RecyclerView的滚动位置需要以下步骤:
getLayoutManager().onSaveInstanceState()
方法获取当前LayoutManager的状态,并将其保存到Bundle中。getLayoutManager().onRestoreInstanceState()
方法,并传入之前保存的状态来恢复RecyclerView的滚动位置。以下是示例代码:
public class MyActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
// 设置布局管理器
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
// 设置适配器
adapter = new MyAdapter(data);
recyclerView.setAdapter(adapter);
// 恢复RecyclerView的滚动位置
if (savedInstanceState != null) {
Parcelable state = savedInstanceState.getParcelable("recycler_state");
recyclerView.getLayoutManager().onRestoreInstanceState(state);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// 保存RecyclerView的滚动位置
Parcelable state = recyclerView.getLayoutManager().onSaveInstanceState();
outState.putParcelable("recycler_state", state);
}
}
在上面的代码中,我们将RecyclerView的滚动位置保存到Bundle中,并在恢复布局后将其恢复到RecyclerView中。
推荐使用腾讯云的产品腾讯云云服务器(CVM)作为云计算平台。腾讯云云服务器(CVM)是一种灵活可扩展的云计算基础设施,为用户提供高性能的虚拟机实例,可以满足各种不同规模和需求的应用场景。
腾讯云云服务器产品介绍链接地址:https://cloud.tencent.com/product/cvm
领取专属 10元无门槛券
手把手带您无忧上云