如何保存在onSaveInstanceState中

时间:2015-10-29 17:42:15

标签: android bundle state android-recyclerview

我在我的应用中使用外部卡片库(gabrielemariotti cardlib)。 特别是我正在使用CardRecyclerView扩展RecyclerView和CardArrayRecyclerViewAdapter扩展BaseRecyclerViewAdapter。 我有两个活动主要活动(使用CardRecyclerView)和ProductCard活动

我的目标是当我从其他活动(ProductCard)返回时或当我打开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);
    }


}

1 个答案:

答案 0 :(得分:1)

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

要保存有关活动状态的其他数据,您必须覆盖     的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并不意味着存储大量数据。

很抱歉,如果某些代码提示不太明确,则很难从移动设备发布答案。

有关更清楚的解释,请参阅此official guide