Android初探:GeoQuiz学习

初学Android,第一个项目:GeoQuiz。

1. 项目演示:

a. 让用户对地理问题作出True/False的回答,并给出提示。

b. 用户不会时,可以作弊

c. 点击作弊后弹出警告

d. 如果用户真的看了答案,给出提示

2. 步骤:

a. 新建一个Android工程(这里用Android Studio实现)

b. 编写界面

一共两个界面:

Android初探:GeoQuiz学习_第1张图片Android初探:GeoQuiz学习_第2张图片

(0) string.xml (项目中所用到的字符串)

这里将项目中所有要显示的字符串都放在这里,便于以后修改(真实的情况是直接写死在界面的xml里面会有warning,强迫症受不了~)


    GeoQuiz
    True
    False
    Correct!
    Incorrect!
    Next
    Prev
    The Pacific Ocean is larger than the Atlantic Ocean.
    The Suez Canal connects the Red Sea and the Indian Ocean.
    The source of the Nile River is in Egypt.
    The Amazon River is the longest river in the Americans.
    Lake Baikal is the world\'s oldest and deepest freshwater lake.
    Cheat!
    Are you sure you want to do this?
    Show Answer
    Cheating is wrong.
    Current question:\n %1$s \n Answer:\n %2$s

 

(1) activity_quiz.xml (第一个界面)

这里笔者喜欢Android Studio最近默认的constraintLayout,直接对着design视图拖控件就可以了。

Android初探:GeoQuiz学习_第3张图片

对于constraintLayout的详细用法请看这里

xml:喜欢对constraintLayout手写xml的请看这篇文章,下面还是把xml文件贴出来:




    

    

 

(2) activity_cheat.xml (第二个界面)

方法同第一个界面,只是个人会微调一下(有时候自动生成的constraint不对称啊!)

Android初探:GeoQuiz学习_第4张图片

同样贴上xml:




    

    

c. 描述逻辑(写代码)

(1)项目用MVC架构写:

Android初探:GeoQuiz学习_第5张图片

Android初探:GeoQuiz学习_第6张图片

(2) Activity联动:

(3) 数据结构(TrueFalse类):

package com.project.geoquiz;

public class TrueFalse {
    private int mQuestion;
    private boolean mTrueQuestion;

    public TrueFalse(int mQuestion, boolean mTrueQuestion) {
        this.mQuestion = mQuestion;
        this.mTrueQuestion = mTrueQuestion;
    }

    public int getQuestion() {
        return mQuestion;
    }

    public boolean isTrueQuestion() {
        return mTrueQuestion;
    }

    public void setQuestion(int Question) {
        this.mQuestion = Question;
    }

    public void setTrueQuestion(boolean TrueQuestion) {
        this.mTrueQuestion = TrueQuestion;
    }
}

(4)测试的Activity:QuizActivity

package com.project.geoquiz;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class QuizActivity extends AppCompatActivity implements View.OnClickListener{

    private static String KEY_INDEX = "index";
    private static boolean isCheated = false;

    private Button mTrueButton;
    private Button mFalseButton;
    private Button mNextButton;
    private Button mCheatButton;
    private TextView textView;
    private TrueFalse[] mQuestions = {new TrueFalse(R.string.question_oceans, true),
            new TrueFalse(R.string.question_mideast, false),
            new TrueFalse(R.string.question_africa, false),
            new TrueFalse(R.string.question_americas, true),
            new TrueFalse(R.string.question_asia, true)
    };

    private int mCurrentIndex = 0;



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


        textView = findViewById(R.id.geo_quiz);

        /*
          对当前题目的索引恢复
         */
        if (savedInstanceState != null) {
            mCurrentIndex = savedInstanceState.getInt(KEY_INDEX);

        }


        textView.setText(mQuestions[mCurrentIndex].getQuestion());

        mTrueButton = findViewById(R.id.true_button);
        mTrueButton.setOnClickListener(this);

        mFalseButton = findViewById(R.id.false_button);
        mFalseButton.setOnClickListener(this);

        mNextButton = findViewById(R.id.next_button);
        mNextButton.setOnClickListener(this);


        mCheatButton = findViewById(R.id.cheat_button);
        mCheatButton.setOnClickListener(this);

    }

    /**
     * 检查答案
     * @param clickedAnswer 用户点击的是true还是false
     */

    private void checkAnswer(boolean clickedAnswer) {
        //正确
        if (clickedAnswer == mQuestions[mCurrentIndex].isTrueQuestion()) {
            Toast.makeText(this, R.string.correct_toast, Toast.LENGTH_SHORT).show();
        }
        //错误
        else {
            Toast.makeText(this, R.string.incorrect_toast, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 更新题目的显示
     */
    private void updateQuestion() {
        if (mCurrentIndex == mQuestions.length - 1) {
            mCurrentIndex = 0;
        }
        else {
            mCurrentIndex++;
        }
        textView.setText(mQuestions[mCurrentIndex].getQuestion());
    }

    /*
    保存当前题目的索引和作弊信息
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(KEY_INDEX, mCurrentIndex);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.true_button:
                checkAnswer(true);
                break;
            case R.id.false_button:
                checkAnswer(false);
                break;
            case R.id.next_button:
                updateQuestion();
                break;
            case R.id.cheat_button:
                Intent intent = new Intent(this, CheatActivity.class);
                intent.putExtra(CheatActivity.EXTRA_CORRECT_ANSWER, mQuestions[mCurrentIndex].isTrueQuestion());
                intent.putExtra(CheatActivity.EXTRA_CURRENT_QUESTION, mQuestions[mCurrentIndex].getQuestion());
                intent.putExtra(CheatActivity.EXTRA_CURRENT_INDEX, mCurrentIndex);
                startActivityForResult(intent, 0);
                break;
                default:
        }
    }


    @Override
    protected void onResume() {
        if (isCheated) {
            Toast.makeText(this, R.string.judgment_toast, Toast.LENGTH_SHORT).show();
        }
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        // 获取作弊结果
        if (requestCode == 0 && resultCode == RESULT_OK) {
            if (data == null) {
                return;
            }
            isCheated = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN, false);

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

(5)作弊的Activity:CheatActivity

package com.project.geoquiz;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class CheatActivity extends AppCompatActivity {
    public static final String EXTRA_CURRENT_QUESTION = "com.project.geoquiz.current_question";
    public static final String EXTRA_CORRECT_ANSWER = "com.project.geoquiz.correct_answer";
    public static final String EXTRA_CURRENT_INDEX = "com.project.geoquiz.current_index";
    public static final String EXTRA_ANSWER_SHOWN = "com.project.geoquiz.answer_shown";
    private static final String KEY_CHEAT_INFO = "cheat_info";
    private int currentQuestion;
    private boolean answerIsTrue;
    private boolean isCheated = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cheat);
        //这里取出第一个Activity的数据

        if (savedInstanceState != null) {
            isCheated = savedInstanceState.getBoolean(KEY_CHEAT_INFO);
        }

        Intent intent = getIntent();
        answerIsTrue = intent.getBooleanExtra(EXTRA_CORRECT_ANSWER, false);
        currentQuestion = intent.getIntExtra(EXTRA_CURRENT_QUESTION, 0);

        setAnswerShownResult(isCheated);

        Button showAnswerButton = findViewById(R.id.show_answer_button);
        showAnswerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //显示答案。
                TextView textView = findViewById(R.id.warning_text);
                textView.setText(String.format(getString(R.string.tell_you_the_answer), getString(currentQuestion), String.valueOf(answerIsTrue)));
                setAnswerShownResult(true);
                isCheated = true;
            }
        });
    }

    /**
     * 设置结果(为MainActivity提供作弊信息)
     * @param isAnswerShown 有没有看答案
     */
    private void setAnswerShownResult(boolean isAnswerShown) {
        Intent data = new Intent();
        data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
        setResult(RESULT_OK, data);
    }

    /**
     * 这个地方为了修复一个bug:作弊者如果点了show answer后旋转屏幕,即可清除作弊信息
     * @param outState 放作弊信息的地方
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(KEY_CHEAT_INFO, isCheated);
        super.onSaveInstanceState(outState);
    }
}

 

你可能感兴趣的:(Android)