Android 如何在屏幕旋转时存储大量数据?

Android 如何在屏幕旋转时存储大量数据?,android,screen-rotation,Android,Screen Rotation,是的,我读过许多其他帖子,但我无法跟上,因为我有很多变量,而不仅仅是一两个。 我正在做一个应用程序(TIC TAC TOE)第一次与景观支持。我正在丢失屏幕旋转的数据 package com.netlify.krupesh.tictactoe; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.vi

是的,我读过许多其他帖子,但我无法跟上,因为我有很多变量,而不仅仅是一两个。

我正在做一个应用程序(TIC TAC TOE)第一次与景观支持。我正在丢失屏幕旋转的数据

package com.netlify.krupesh.tictactoe;

import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    // 0 for zero and 1 for X
    // 2 for empty
    boolean gameActive = true;
    int[] gameState = {2,2,2,2,2,2,2,2,2};
    int[][] winningPositions = {{0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}};

    int activePlayer = 0;
    int[] playerScores = {0,0};

    // Show Symbol on Tap
    public void showSymbol(View view){
        // Set Player Scores
        TextView player1 = (TextView) findViewById(R.id.p1Score);
        TextView player2 = (TextView) findViewById(R.id.p2Score);


        player1.setText(playerScores[0]+"");
        player2.setText(playerScores[1]+"");

        // Get Symbol Info
        ImageView symbol = (ImageView) view;
        int tappedSymbol = Integer.parseInt(symbol.getTag().toString());

        // Update Game state Array
        if(gameState[tappedSymbol]==2 && gameActive) {
            gameState[tappedSymbol] = activePlayer;

            // Show Symbol with Animation
            symbol.setAlpha(0f);
            if (activePlayer == 0) {
                symbol.setImageResource(R.drawable.zero);
                activePlayer = 1;
                showCurrentPlayer(2);

            } else {
                symbol.setImageResource(R.drawable.cross);
                activePlayer = 0;
                showCurrentPlayer(1);
            }
            symbol.animate().alpha(1).setDuration(400);

            checkDraw(gameState);

            for (int[] winningPosition : winningPositions) {
                if (gameState[winningPosition[0]] == gameState[winningPosition[1]] && gameState[winningPosition[1]] == gameState[winningPosition[2]] && gameState[winningPosition[0]] != 2) {
                    showCurrentPlayer(0);
                    // Pause The Game
                    gameActive = false;

                    // Won the Game
                    String winningPlayer ;
                    if (gameState[winningPosition[0]] == 0) winningPlayer = "Player 1";
                    else winningPlayer = "Player 2";
                    Toast.makeText(this, winningPlayer + " won!", Toast.LENGTH_SHORT).show();

                    // Update Scores
                    playerScores[gameState[winningPosition[0]]]++;
                    player1.setText(playerScores[0] + "");
                    player2.setText(playerScores[1] + "");
                }
            }
        }
    }


    public void resetBoard(View view){
        android.support.v7.widget.GridLayout board = (android.support.v7.widget.GridLayout)findViewById(R.id.gridLayout);
        for(int i=0; i<board.getChildCount(); i++) {
            ImageView symbol = (ImageView) board.getChildAt(i);
            symbol.setImageDrawable(null);
        }
        for(int i=0; i<gameState.length; i++ ){
            gameState[i] = 2;
        }
        gameActive = true;
        activePlayer = 0;
        showCurrentPlayer(1);
    }

    public void checkDraw(int[] gamestate){
        for(int i =0; i<gamestate.length; i++){
            if(gamestate[i]==2){
                return;
            }
        }
        showCurrentPlayer(0);
        Toast.makeText(this, "Match Draw!", Toast.LENGTH_SHORT).show();
    }

    public void resetAll(View view){
        resetBoard(view);
        playerScores[0]=0; playerScores[1]=0;
        TextView player1 = (TextView) findViewById(R.id.p1Score);
        TextView player2 = (TextView) findViewById(R.id.p2Score);
        player1.setText(playerScores[0] + "");
        player2.setText(playerScores[1] + "");
        showCurrentPlayer(1);
    }

    public void showCurrentPlayer(int i){
        TextView player1Heading = (TextView) findViewById(R.id.subheading1);
        TextView player2Heading = (TextView) findViewById(R.id.subheading2);
        if(i==1){
            player1Heading.setTextColor(getResources().getColor(R.color.colorPlayer1));
            player1Heading.setTypeface(null, Typeface.BOLD);
            player2Heading.setTextColor(getResources().getColor(R.color.colorHeading));
            player2Heading.setTypeface(null, Typeface.NORMAL);
        }
        if(i==2){
            player2Heading.setTextColor(getResources().getColor(R.color.colorPlayer2));
            player2Heading.setTypeface(null, Typeface.BOLD);
            player1Heading.setTextColor(getResources().getColor(R.color.colorHeading));
            player1Heading.setTypeface(null, Typeface.NORMAL);
        }
        if(i==0){
            player1Heading.setTextColor(getResources().getColor(R.color.colorHeading));
            player1Heading.setTypeface(null, Typeface.NORMAL);
            player2Heading.setTextColor(getResources().getColor(R.color.colorHeading));
            player2Heading.setTypeface(null, Typeface.NORMAL);
        }
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ===================== Hide Status Bar ========================== //
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // ================================================================ //

        setContentView(R.layout.activity_main);
        showCurrentPlayer(1);
    }
}
package com.netlify.krupesh.tictactoe;
导入android.graphics.Typeface;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.view.view;
导入android.view.Window;
导入android.view.WindowManager;
导入android.widget.ImageView;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MainActivity扩展了AppCompatActivity{
//0表示零,1表示X
//2为空
布尔gameActive=true;
int[]配子状态={2,2,2,2,2,2,2,2};
int[]winning positions={0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6};
int activePlayer=0;
int[]playerScores={0,0};
//点击显示符号
公共无效显示符号(视图){
//设定球员得分
TextView播放器1=(TextView)findViewById(R.id.p1Score);
TextView播放器2=(TextView)findViewById(R.id.p2Score);
player1.setText(playerCores[0]+“”);
player2.setText(playerCores[1]+“”);
//获取符号信息
ImageView符号=(ImageView)视图;
int-tappedSymbol=Integer.parseInt(symbol.getTag().toString());
//更新游戏状态数组
如果(游戏状态[tappedSymbol]==2&&gameActive){
游戏状态[tappedSymbol]=活动玩家;
//用动画显示符号
符号。setAlpha(0f);
如果(activePlayer==0){
symbol.setImageResource(R.drawable.zero);
activePlayer=1;
showCurrentPlayer(2);
}否则{
symbol.setImageResource(R.drawable.cross);
activePlayer=0;
showCurrentPlayer(1);
}
symbol.animate().alpha(1).setDuration(400);
勾选(游戏状态);
对于(int[]winningPosition:winningPositions){
如果(游戏状态[winningPosition[0]==gameState[winningPosition[1]]和&gameState[winningPosition[1]==gameState[winningPosition[2]]和&gameState[winningPosition[0]!=2){
showCurrentPlayer(0);
//暂停比赛
gameActive=false;
//赢得比赛
弦乐赢家;
如果(游戏状态[winningPosition[0]]==0)winningPlayer=“玩家1”;
else winningPlayer=“玩家2”;
Toast.makeText(这个,winningPlayer+“赢了!”,Toast.LENGTH_SHORT.show();
//更新分数
玩家核心[gameState[winningPosition[0]]]++;
player1.setText(playerCores[0]+“”);
player2.setText(playerCores[1]+“”);
}
}
}
}
公共无效重置板(视图){
android.support.v7.widget.GridLayout board=(android.support.v7.widget.GridLayout)findviewbyd(R.id.GridLayout);

对于(int i=0;i@krupesh Anadkat我作为一名新手感到沮丧,但@commonware是一名经验丰富的开发人员,已经在游戏中工作了几天

按照他的建议去做,确保你学到了他概述的基本原理,而不是一气呵成,或者只是为了它而匆忙地去做一些事情

然而,今天是你的幸运日,所以我会用一些代码片段来宠坏你(我们千禧一代程序员喜欢简单是的,我说了!!!)阅读youngling并学习

您在这里面临的问题是设备配置的更改

在您的情况下,屏幕方向将发生变化

每次用户旋转屏幕时,Android操作系统都会重新创建一个新的活动。Android操作系统意味着没有伤害,它只是在检查是否有更好的资源用于新方向,如果有,它可以使用这些资源

这是你痛苦的根源。现在让我们继续努力,帮助你走出困境

您可以使用活动的类方法来解决此问题。在全能的Android OS杀死您的活动之前,将在活动的生命周期中调用方法onSaveInstanceState()。在您的类中覆盖onSaveInstanceState()并将您想要的数据保存到捆绑包中,onSaveInstanceState()将其作为参数

然后在活动的onCreate()中检查savedInstanceState是否不为空,如果不为空,则检索数据

不过要小心;最好将基本数据类型保存到捆绑包或可序列化的对象,以避免检索过时或不再有效的数据

请参阅下面我的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);
    }

}


玩得开心!

。或者,使用保存的实例状态
。这对我来说就像希腊语和拉丁语一样,你能分享一个代码片段吗,请看。@commonsware我建议你花点时间真正地学习材料,而不是仅仅依靠随机的代码片段。读一本涵盖这些主题的书。或者,参加一门涵盖这些主题的课程ese主题(直播、Udacity视频等).是的,当然。我在udacity为android初学者上了2门课,我可以创建一个漂亮的UI Tic Tac Toe,功能齐全。在Playstore中只需进行几次润色。我可以一直学习。太好了!如果这是谷歌的官方课程,它应该涵盖
ViewModel
或保存的实例状态
Bundle
。如果你愿意的话他们说这些课程既不包括苏