如何在 onSaveInstanceState 中保存

How to save in onSaveInstanceState

我在我的应用程序中使用外部卡片库 (gabrielemariotti cardlib)。 特别是我正在使用 CardRecyclerView extends RecyclerView 和 CardArrayRecyclerViewAdapter extends BaseRecyclerViewAdapter。 我有两个活动 Main Activity(使用 CardRecyclerView)和 ProductCard activity

我的目标是在我从其他活动 (ProductCard) 返回或打开 MainActivity 方向时将所有卡片保存在 MainActivity 中。 不幸的是,我不明白如何在 onSaveInstanceState 中保存我的 'mRecyclerView'。有人可以帮忙吗?

package com.example.dmitry.myfoodbasket;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.io.Serializable;
import java.util.ArrayList;

import it.gmariotti.cardslib.library.cards.actions.BaseSupplementalAction;
import it.gmariotti.cardslib.library.cards.actions.IconSupplementalAction;
import it.gmariotti.cardslib.library.cards.material.MaterialLargeImageCard;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardHeader;
import it.gmariotti.cardslib.library.recyclerview.internal.CardArrayRecyclerViewAdapter;
import it.gmariotti.cardslib.library.recyclerview.view.CardRecyclerView;

public class MainActivity extends AppCompatActivity {
    final String LOG_TAG = "myLogs";
    ArrayList<BaseSupplementalAction> actions;
    ArrayList<Card> cards;
    MaterialLargeImageCard card;
    CardArrayRecyclerViewAdapter mCardArrayAdapter;
    CardRecyclerView mRecyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(LOG_TAG, "onCreate");


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();*/
                cards.add(card);
                mCardArrayAdapter.notifyDataSetChanged();
            }
        });



        cards = new ArrayList<Card>();
        card =
                MaterialLargeImageCard.with(this)
                        .setTextOverImage("Italian Beaches")
                        .useDrawableId(R.drawable.im_beach)
                        .setupSupplementalActions(R.layout.carddemo_native_material_supplemental_actions_large_icon,actions )
                        .build();
        cards.add(card);
        card.setOnClickListener(new Card.OnCardClickListener() {
            @Override
            public void onClick(Card card, View view) {
                Intent intent=new Intent(MainActivity.this,ProductCard.class);
                startActivity(intent);




            }});

        actions = new ArrayList<BaseSupplementalAction>();

        IconSupplementalAction t1 = new IconSupplementalAction(this, R.id.ic1);
        t1.setOnActionClickListener(new BaseSupplementalAction.OnActionClickListener() {
            @Override
            public void onClick(Card card, View view) {
                Toast.makeText(MainActivity.this, " Click on Text SHARE ", Toast.LENGTH_SHORT).show();
            }
        });
        actions.add(t1);

        IconSupplementalAction t2 = new IconSupplementalAction(this, R.id.ic2);
        t2.setOnActionClickListener(new BaseSupplementalAction.OnActionClickListener() {
            @Override
            public void onClick(Card card, View view) {
                Toast.makeText(MainActivity.this," Click on Text LEARN ", Toast.LENGTH_SHORT).show();
            }
        });
        actions.add(t2);

        IconSupplementalAction t3 = new IconSupplementalAction(this, R.id.ic3);
        t3.setOnActionClickListener(new BaseSupplementalAction.OnActionClickListener() {
            @Override
            public void onClick(Card card, View view) {
                Toast.makeText(MainActivity.this, " Карточка удалена ", Toast.LENGTH_SHORT).show();
                cards.remove(card);
                mCardArrayAdapter.notifyDataSetChanged();
            }
        });
        actions.add(t3);


        mCardArrayAdapter = new CardArrayRecyclerViewAdapter(this, cards);
        mRecyclerView = (CardRecyclerView) this.findViewById(R.id.carddemo_recyclerview);
        mRecyclerView.setHasFixedSize(false);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        if (mRecyclerView != null) {
            mRecyclerView.setAdapter(mCardArrayAdapter);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}

您的 activity 将在用户每次旋转屏幕时被销毁并重新创建。当屏幕改变方向时,系统会破坏并重新创建前景 activity。

要保存有关 activity 状态的其他数据,您必须覆盖 onSaveInstanceState() 回调方法

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
 savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
 savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
 super.onSaveInstanceState(savedInstanceState); }

现在您可以在上面的 Bundle 实例中保存特定的字符串、整数或事件自定义 Parelable 对象。 当您的 Activity 重新创建时,只需检查 onCreate() 中的 Bundle onSavedInstance 是否为 null

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first

 // Check whether we're recreating a previously destroyed instance
 if (savedInstanceState != null) {
 // Restore value of members from saved state and populare your RecyclerView again
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
 } else {
 // Probably initialize members with default values for a new instance
}

您可以将上面的内容替换为您要保存的数据,然后使用您保存在 savedInstance 中的数据作为键值对重新填充您的视图,如 RecyclerView 等。

请记住,Bundle 并不意味着存储大量数据。

抱歉,如果某些代码标识不是很清楚,那么 post 从移动设备上回答就更难了。

如需更清楚的解释,请参阅此 official guide