@克鲁佩什·阿纳德卡特
作为一个新手我感到沮丧,但是
@ CommonsWare
是一个经验丰富的开发者,已经在游戏中玩了几天。
听从他的建议,并确保你学习他概述的基本原理,而不是为了这个目的而冲破或匆忙去建造一些东西。
然而今天是你的幸运日,所以我会用一些代码片段宠坏你(我们千禧年程序员喜欢它容易是的,我说了!!!!)读杨凌的文章并学习。
你现在面临的问题是
设备配置
改变。
以你为例
屏幕方向
改变。
每次用户旋转屏幕
安卓系统
再造你
活动
一个新的。这个
安卓系统
也就是说,它只是想提高效率,检查新方向是否有更好的资源,如果有,它可以使用这些资源。
这是你痛苦的根源。现在,让我们来帮助你,伙计。
你可以使用
活动的
类方法来解决这个问题。在全能者面前
安卓系统
杀死你的活动的方法
OnSaveInstanceState()。
将在活动的生命周期中调用。在您的类中,您重写
OnSaveInstanceState()。
并将您想要的数据保存到
束
哪一个
OnSaveInstanceState()。
作为一个论点。
然后在你的活动中
OnCuto()
你检查是否
倚仗
如果您检索的数据不为空,则不为空。
不过要当心,最好的办法是
基本数据类型
到
束
或是
可串行化的
以避免检索过时的数据,即过期或不再有效。
请参见下面的代码段了解我的savedataacrossscreenorientation活动
package com.demo.android.savedataacrossscreenrotationdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SaveDataAcrossScreenOrientation extends AppCompatActivity {
// Key to be used for the key: value pair to be saved to the bundle
private static final String KEY_GREETING_TEXT = "greeting_text";
// The text currently displayed to the screen
private String mCurrentDisplayedText;
private TextView mGreetingTextView;
private Button mSpanishButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get references to the button and textview
mGreetingTextView = (TextView) findViewById(R.id.greeting_text_view);
mSpanishButton = (Button) findViewById(R.id.change_greeting_button);
// If mCurrentDisplayedText is inside the bundle retrieve and display it on screen
if(savedInstanceState != null) {
mCurrentDisplayedText = savedInstanceState.getString(KEY_GREETING_TEXT, "");
if (mCurrentDisplayedText != "") {
mGreetingTextView.setText(mCurrentDisplayedText);
}
}
// Set a listener on the spanish button
mSpanishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Change the english text to spanish when the button is clicked
mGreetingTextView.setText(R.string.spanish_greeting);
// Get the text currently shown in the text view
mCurrentDisplayedText = (String) mGreetingTextView.getText(); // Calling getText() returns a CharSequence cast it to a string
}
});
}
// Override onSaveInstanceState(Bundle savedInstanceState) and save mCurrentDisplayedText to the bundle
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString(KEY_GREETING_TEXT, mCurrentDisplayedText);
}
}
See video demo here
玩得高兴!