简体   繁体   English

如何在Recyclerview中使用onSaveInstance方法

[英]How to use onSaveInstance method with Recyclerview

I have an App which should keep all the data displayed into Recycler when the screen is rotated. 我有一个应用程序,它应该在旋转屏幕时将所有数据显示在Recycler中。 the recycler receives data from a Custom Array List. 回收站从自定义阵列列表中接收数据。 there is also a second variable used to set the Uri of the VideoView inside the adapter. 还有第二个变量用于在适配器内设置VideoView的Uri。

already tried onSave and onRestoreIntance. 已经尝试过onSave和onRestoreIntance。 maybe I have used them wrong. 也许我用错了。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    // Variables-----------------------------------------

     recyclerView = findViewById(R.id.recyclerView);
    Button video = findViewById(R.id.video);
    Button camera = findViewById(R.id.camera);
    Button send = findViewById(R.id.send);
    final EditText editText = findViewById(R.id.editText);


    // Layout Manager------------------------------------------------

    linearLayoutManager = new LinearLayoutManager(MainActivity.this);
    linearLayoutManager.setStackFromEnd(true);
    RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setItemAnimator(itemAnimator);


    // Adapter-----------------------------------------

        //adapter.notifyDataSetChanged();
        adapter =  new myAdapter(dati, this);
        recyclerView.setAdapter(adapter);



    // Click Listener Video button---------------------------------------- 
    video.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            startActivityForResult(intent,0);
        }
    });

    // Click Listener Camera button--------------------------------------
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,1);
        }
    });

    // Click Listener Send button-----------------------------------------
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String string = editText.getText().toString();
            dati.add(new ModelloDati(0,string));
            adapter.notifyItemInserted(dati.size());
            editText.getText().clear();
            recyclerView.smoothScrollToPosition(dati.size());
            closeKeyboard();
        }
    });

    if(savedInstanceState != null)



linearLayoutManager.onRestoreInstanceState(
savedInstanceState.getParcelable("STATO_LISTA"));

}


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable  
Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode){
        case 0:
            try {
                Uri contentURI = data.getData();
                passUri = contentURI;
                String recordedVideoPath = getPath(contentURI);
                saveVideoToInternalStorage(recordedVideoPath);
                dati.add(new ModelloDati(2, contentURI));
                adapter.notifyItemInserted(dati.size());
                recyclerView.smoothScrollToPosition(dati.size());

            }catch (Throwable o){Log.i("CAM","User aborted action");}
        case 1:
            try {
                Bitmap bitmap = (Bitmap)data.getExtras().get("data");
                dati.add(new ModelloDati(1,bitmap));
                adapter.notifyItemInserted(dati.size());
                recyclerView.smoothScrollToPosition(dati.size());


            }catch(Throwable o){
                Log.i("CAM","User aborted action");
            }

    }


}


@Override
protected void onResume() {
    super.onResume();

    if (saveList != null) {
        linearLayoutManager.onRestoreInstanceState(saveList);
    }
}


@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveList = linearLayoutManager.onSaveInstanceState();
    outState.putParcelable("STATO_LISTA",saveList);
}


@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if(savedInstanceState != null)
       savedInstanceState.getParcelable("STATO_LISTA");
}

}

Android offers Architecture components which helps you deal with those kind of situations. Android提供的架构组件可以帮助您处理这些情况。 For example ViewModel 例如ViewModel

The Android framework manages the lifecycles of UI controllers, such as activities and fragments. Android框架管理UI控制器的生命周期,例如活动和片段。 The framework may decide to destroy or re-create a UI controller in response to certain user actions or device events that are completely out of your control. 框架可以决定销毁或重新创建UI控制器以响应某些完全不受您控制的用户操作或设备事件。

If the system destroys or re-creates a UI controller, any transient UI-related data you store in them is lost. 如果系统销毁或重新创建UI控制器,则存储在其中的任何瞬态UI相关数据都将丢失。 For example, your app may include a list of users in one of its activities. 例如,您的应用可能会在其中一项活动中包含用户列表。 When the activity is re-created for a configuration change, the new activity has to re-fetch the list of users. 为配置更改重新创建活动时,新活动必须重新获取用户列表。 For simple data, the activity can use the onSaveInstanceState() method and restore its data from the bundle in onCreate(), but this approach is only suitable for small amounts of data that can be serialized then deserialized, not for potentially large amounts of data like a list of users or bitmaps. 对于简单数据,活动可以使用onSaveInstanceState()方法并从onCreate()中的包中恢复其数据,但此方法仅适用于可以序列化然后反序列化的少量数据,而不适用于潜在的大量数据像用户列表或位图。

So basically you can hold your dataset for your adapter in your ViewModel and inside onCreate get the data and set it into your adapter. 因此,基本上您可以在ViewModel中保存适配器的数据集,并在onCreate内部获取数据并将其设置到适配器中。

MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
new adapter(model.getData(),this); // just for the example.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM