Android studio: Interactive Story App -> как с сохранением, где вы остановились? - PullRequest
0 голосов
/ 28 марта 2020

Уважаемое сообщество

Я не профессионал, очевидно, у меня есть вопрос, связанный с этим проектом gitHub: https://github.com/treehouse/android-interactive-story Основные кодовые части: Функциональность истории: Выбор. java

public class Choice {
private String mText;
private int mNextPage;

public Choice(String text, int nextPage) {
    mText = text;
    mNextPage = nextPage;
}

public String getText() {
    return mText;
}

public void setText(String text) {
    mText = text;
}

public int getNextPage() {
    return mNextPage;
}

public void setNextPage(int nextPage) {
    mNextPage = nextPage;
}
}

Стр. java

public class Page {
private int mImageId;
private String mText;
private Choice mChoice1;
private Choice mChoice2;
private boolean mIsFinal = false;

public Page(int imageId, String text, Choice choice1, Choice choice2) {
    mImageId = imageId;
    mText = text;
    mChoice1 = choice1;
    mChoice2 = choice2;
}

public boolean isFinal() {
    return mIsFinal;
}

public void setFinal(boolean isFinal) {
    mIsFinal = isFinal;
}

public Page(int imageId, String text) {
    mImageId = imageId;
    mText = text;
    mChoice1 = null;
    mChoice2 = null;
    mIsFinal = true;

}

public int getImageId() {
    return mImageId;
}

public String getText() {
    return mText;
}

public void setText(String text) {
    mText = text;
}

public Choice getChoice1() {
    return mChoice1;
}

public void setChoice1(Choice choice1) {
    mChoice1 = choice1;
}

public Choice getChoice2() {
    return mChoice2;
}

public void setChoice2(Choice choice2) {
    mChoice2 = choice2;
}

public void setImageId(int id) {
    mImageId = id;
}
}

История. java

public class Story {
private Page[] mPages;

public Story() {
    mPages = new Page[7];

    mPages[0] = new Page(
            R.drawable.page0,
            "On your return trip from studying Saturn's rings, you hear a distress signal that seems to be coming from the surface of Mars. It's strange because there hasn't been a colony there in years. Even stranger, it's calling you by name: \"Help me, %1$s, you're my only hope.\"",
            new Choice("Stop and investigate", 1),
            new Choice("Continue home to Earth", 2));

    mPages[1] = new Page(
            R.drawable.page1,
            "You deftly land your ship near where the distress signal originated. You didn't notice anything strange on your fly-by, but there is a cave in front of you. Behind you is an abandoned rover from the early 21st century.",
            new Choice("Explore the cave", 3),
            new Choice("Explore the rover", 4));

    mPages[2] = new Page(
            R.drawable.page2,
            "You continue your course to Earth. Two days later, you receive a transmission from HQ saying that they have detected some sort of anomaly on the surface of Mars near an abandoned rover. They ask you to investigate, but ultimately the decision is yours because your mission has already run much longer than planned and supplies are low.",
            new Choice("Head back to Mars to investigate", 4),
            new Choice("Continue home to Earth", 6));

    mPages[3] = new Page(
            R.drawable.page3,
            "Your EVA suit is equipped with a headlamp, which you use to navigate the cave. After searching for a while your oxygen levels are starting to get pretty low. You know you should go refill your tank, but there's a very faint light up ahead.",
            new Choice("Refill at ship and explore the rover", 4),
            new Choice("Continue towards the faint light", 5));

    mPages[4] = new Page(
            R.drawable.page4,
            "The rover is covered in dust and most of the solar panels are broken. But you are quite surprised to see the on-board system booted up and running. In fact, there is a message on the screen: \"%1$s, come to 28.543436, -81.369031.\" Those coordinates aren't far, but you don't know if your oxygen will last there and back.",
            new Choice("Explore the coordinates", 5),
            new Choice("Return to Earth", 6));

    mPages[5] = new Page(
            R.drawable.page5,
            "After a long walk slightly uphill, you end up at the top of a small crater. You look around, and are overjoyed to see your favorite android, %1$s-S1124. It had been lost on a previous mission to Mars! You take it back to your ship and fly back to Earth.");

    mPages[6] = new Page(
            R.drawable.page6,
            "You arrive home on Earth. While your mission was a success, you forever wonder what was sending that signal. Perhaps a future mission will be able to investigate...");
}

public Page getPage(int pageNumber) {
    return mPages[pageNumber];
}
}

Основная деятельность (игровая активность): StoryActivity. java

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import teamtreehouse.com.interactivestory.R;
import teamtreehouse.com.interactivestory.model.Page;
import teamtreehouse.com.interactivestory.model.Story;


public class StoryActivity extends Activity {

public static final String TAG = StoryActivity.class.getSimpleName();

private Story mStory = new Story();
private ImageView mImageView;
private TextView mTextView;
private Button mChoice1;
private Button mChoice2;
private String mName;
private Page mCurrentPage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_story);

    Intent intent = getIntent();
    mName = intent.getStringExtra(getString(R.string.key_name));

    if (mName == null) {
        mName = "Friend";
    }
    Log.d(TAG, mName);

    mImageView = (ImageView)findViewById(R.id.storyImageView);
    mTextView = (TextView)findViewById(R.id.storyTextView);
    mChoice1 = (Button)findViewById(R.id.choiceButton1);
    mChoice2 = (Button)findViewById(R.id.choiceButton2);

    loadPage(0);
}

private void loadPage(int choice) {
    mCurrentPage = mStory.getPage(choice);

    Drawable drawable = getResources().getDrawable(mCurrentPage.getImageId());
    mImageView.setImageDrawable(drawable);

    String pageText = mCurrentPage.getText();
    // Add the name if placeholder included. Won't add if no placeholder
    pageText = String.format(pageText, mName);
    mTextView.setText(pageText);

    if (mCurrentPage.isFinal()) {
        mChoice1.setVisibility(View.INVISIBLE);
        mChoice2.setText("PLAY AGAIN");
        mChoice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    else {
        mChoice1.setText(mCurrentPage.getChoice1().getText());
        mChoice2.setText(mCurrentPage.getChoice2().getText());

        mChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int nextPage = mCurrentPage.getChoice1().getNextPage();
                loadPage(nextPage);
            }
        });

        mChoice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int nextPage = mCurrentPage.getChoice2().getNextPage();
                loadPage(nextPage);
            }
        });
    }
}

}

У меня вопрос, как я мог настроить «Сохранить, где вы остановились» в этом приложении. Сохранить, где вы остановились: Идея заключается в том, что если я хочу закрыть приложение, например, на третьей странице истории ->, тогда я хочу нажать btn для сохранения, а затем, когда я возвращаюсь в приложение, я могу нажать btn в другом действии (например, под названием сохранить активность), и после того, как я нажал btn, я возвращаюсь на третью страницу истории, где я остановился.

Не могли бы вы привести пример кода для этой идеи. Я знаю, что могу / должен сделать это с общими предпочтениями, но я не знаю как. И если вы отправите мне документацию -> это, к сожалению, мне тоже не поможет. Я уже потратил много времени на поиск и чтение и не смог найти решение (как я уже сказал, я не профессионал). Так что пример кода будет очень добрым.

Заранее большое спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...