Android 简单案例:onSaveInstanceState 和 onRestoreInstanceState

Posted 好久不见

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 简单案例:onSaveInstanceState 和 onRestoreInstanceState相关的知识,希望对你有一定的参考价值。

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public final class MultiRes extends Activity {

    private int mCurrentPhotoIndex = 0;
    private int[] mPhotoIds = new int[] { R.drawable.sample_0,
            R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6,
            R.drawable.sample_7 };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        showPhoto(mCurrentPhotoIndex);

        // Handle clicks on the ‘Next‘ button.
        Button nextButton = (Button) findViewById(R.id.next_button);
        nextButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mCurrentPhotoIndex = (mCurrentPhotoIndex + 1)
                        % mPhotoIds.length;
                showPhoto(mCurrentPhotoIndex);
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("photo_index", mCurrentPhotoIndex);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        mCurrentPhotoIndex = savedInstanceState.getInt("photo_index");
        showPhoto(mCurrentPhotoIndex);
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void showPhoto(int photoIndex) {
        ImageView imageView = (ImageView) findViewById(R.id.image_view);
        imageView.setImageResource(mPhotoIds[photoIndex]);

        TextView statusText = (TextView) findViewById(R.id.status_text);
        statusText.setText(String.format("%d/%d", photoIndex + 1,
                mPhotoIds.length));
    }
}

 

以上是关于Android 简单案例:onSaveInstanceState 和 onRestoreInstanceState的主要内容,如果未能解决你的问题,请参考以下文章

Android 简单案例:onSaveInstanceState 和 onRestoreInstanceState

8.Android-简单的登录案例编写

安卓案例2:简单登录界面和保存信息

Android 简单案例:继承BaseAdapter实现Adapter

Android开发获取当前经纬度和详细位置信息(原生代码实现)简单案例

Android:安卓学习笔记之共享元素的简单理解和使用