Android编程权威指南-第5章:挑战练习

QuizActivity.java

package com.onevol.app;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.geoquiz.R;

public class QuizActivity extends Activity {

    private static final String KEY_INDEX = "index";
    //新建一个常量作为Bundle的键,将mCurrectIndex变量作为Bundle的值。
    //用于在翻转设备后,保持题目号码不变。
    private static final String KEY_CHEAT = "cheater";
    //作为值mIsCheater的键。用于保持是否查看过答案的Boolean值不变。
    private static final String KEY_NUMBER = "number";
    //作为值list的键。用于保持保存看过答案的题目号的容器不变。

    private Button mTureButton;
    private Button mFalseButton;
    private Button mPrevButton;
    private Button mNextButton;
    private Button mCheatButton;
    private TextView mQuestionTextView;
    private TrueFalse[] mQuestionBank = new TrueFalse[] {
            new TrueFalse(R.string.question_africa, false),
            new TrueFalse(R.string.question_americas, true),
            new TrueFalse(R.string.question_asia, true),
            new TrueFalse(R.string.question_mideast, false),
            new TrueFalse(R.string.question_oceans, true),
    };
    private int mCurrectIndex = 0;//题目号码
    private boolean mIsCheater;//是否看过答案
    private int mClickedNumber;//看过答案的题目号码
    private ArrayList list = new ArrayList();//保存看过答案的题目号码的容器

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null){
            return;
        }
        mIsCheater = data.getBooleanExtra("answer_shown", false);//接受返回的是否看过答案
        mClickedNumber = data.getIntExtra("clicked_number", 0);//接受看过答案的题目号码
        if((Integer)mClickedNumber != null){
            list.add(mClickedNumber);//将看过答案的题目号码添加到容器里
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);

        mTureButton = (Button) findViewById(R.id.ture_button);
        mFalseButton = (Button) findViewById(R.id.false_button);
        mPrevButton = (Button) findViewById(R.id.prev_button);
        mNextButton = (Button) findViewById(R.id.next_button);
        mCheatButton = (Button) findViewById(R.id.cheat_button);

        mQuestionTextView = (TextView) findViewById(R.id.question_text);

        if(savedInstanceState != null){//在onCreate()方法中检查储存的Bundle信息。在UpdateQuestion()方法前检查。
            mCurrectIndex = savedInstanceState.getInt(KEY_INDEX);
            mIsCheater = savedInstanceState.getBoolean(KEY_CHEAT);
            list = savedInstanceState.getIntegerArrayList(KEY_NUMBER);
            //保持屏幕翻转前的数据不变
        }
        updateQuestion();

        mTureButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//              Toast.makeText(QuizActivity.this, "Incorrect", Toast.LENGTH_SHORT).show();
                checkAnswer(true);
            }
        });
        mFalseButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//              Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                checkAnswer(false);
            }
        });
        mPrevButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mIsCheater = false;//初始化是否看过答案的值
                if(mCurrectIndex == 0){
                    int question = mQuestionBank[mQuestionBank.length -1].getQuestion();
                    mQuestionTextView.setText(question);
                    mCurrectIndex = 4;
                } else{
                    mCurrectIndex = (mCurrectIndex -1);
                    updateQuestion();
                }
            }

        });
        mNextButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mCurrectIndex = (mCurrectIndex + 1) % mQuestionBank.length;
                mIsCheater = false;//初始化是否看过答案的值
                updateQuestion();
            }

        });
        mCheatButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(QuizActivity.this, CheatActivity.class);
                boolean answerIsTrue = mQuestionBank[mCurrectIndex].isTrueQuestion();
                intent.putExtra("answer", answerIsTrue);//将获取的答案传到intent中
                intent.putExtra("number", mCurrectIndex);//将现在的题号传到intent中
//              startActivity(intent);
                startActivityForResult(intent, 0);
            }
        });
        mQuestionTextView.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mCurrectIndex = (mCurrectIndex + 1) % mQuestionBank.length;
                mIsCheater = false;//初始化是否看过答案的值
                updateQuestion();
            }
        });
    }
    private void updateQuestion() {
        int question = mQuestionBank[mCurrectIndex].getQuestion();
        mQuestionTextView.setText(question);
    }

    private void checkAnswer (boolean userPressedTrue){
        boolean answerIsTrue = mQuestionBank[mCurrectIndex].isTrueQuestion();
        if(mIsCheater || list.contains(mCurrectIndex)){//检查是否看过是看过的答案或现在的题号是否被包含在容器中
            Toast.makeText(this, "cheating is wrong.", Toast.LENGTH_SHORT).show();
        } else{
            if(userPressedTrue == answerIsTrue){
                Toast.makeText(this, "Correct", Toast.LENGTH_SHORT).show();
            } else{
                Toast.makeText(this, "Incorrect", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putInt(KEY_INDEX, mCurrectIndex);
        //将mCurrectIndex(题号)储存到Bundle中。
        savedInstanceState.putBoolean(KEY_CHEAT, mIsCheater);
        //将是否看过答案的值储存
        savedInstanceState.putIntegerArrayList(KEY_NUMBER, list);
        //将保存看过答案的题目号的容器储存
    }

}

出现的错误java.lang.NullPointerException
private ArrayList list; 这一行没有实例化ArrayList。改为private ArrayList list = new ArrayList();
CheatActivity.java

package com.onevol.app;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.example.geoquiz.R;

public class CheatActivity extends Activity {

    private static final String KEY_CLICK = "click";
    private boolean mAnswerIsTrue;
    private boolean mIsClick;
    private TextView mAnswerTextView;
    private Button mShowAnswer;
    private int mNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cheat);

        mAnswerIsTrue = getIntent().getBooleanExtra("answer", false);//得到答案
        mNumber = getIntent().getIntExtra("number", 0);//得到题号
        mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
        mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
        if(savedInstanceState != null){//保持屏幕翻转后 查看答案的按钮是否被点击过的值不变
            mIsClick = savedInstanceState.getBoolean(KEY_CLICK);
            if(mAnswerIsTrue){//并显示答案
                mAnswerTextView.setText(R.string.true_button);
            } else {
                mAnswerTextView.setText(R.string.false_button);
            }
        }
        mIsClick=false;//初始化查看答案的按钮是否被点击过
        setAnswerShownResult(mIsClick);//发送没看过答案
        mShowAnswer.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(mAnswerIsTrue){//并显示答案
                    mAnswerTextView.setText(R.string.true_button);
                } else {
                    mAnswerTextView.setText(R.string.false_button);
                }
                mIsClick = true;
                setAnswerShownResult(mIsClick);//发送看过答案

            }
        });
    }
    private void setAnswerShownResult(boolean isAnswerShown){
        Intent intent = new Intent();
        intent.putExtra("answer_shown", isAnswerShown);//传出是否看过答案的值
        if(isAnswerShown){//如果看过答案,就将该题号传出
            intent.putExtra("clicked_number", mNumber);
        }
        setResult(RESULT_OK, intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putBoolean(KEY_CLICK, mIsClick);
        //保存查看答案的按钮是否被点击过的值
    }

}

activity_quiz.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView 
        android:id="@+id/question_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp"
        />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button 
            android:id="@+id/ture_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/true_button"/>
        <Button 
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/false_button"/>
    LinearLayout>
    <Button 
        android:id="@+id/cheat_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cheat_button"/>
    <LinearLayout 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button 
            android:id="@+id/prev_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/prev_button"
            android:drawableLeft="@drawable/arrow_left"
            android:drawablePadding="4dp"/>
        <Button 
            android:id="@+id/next_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/next_button"
            android:drawableRight="@drawable/arrow_right"
            android:drawablePadding="4dp"/>
    LinearLayout>

LinearLayout>

activity_cheat.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center" >

    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp"
        android:text="@string/warning_text"/>
    <TextView
        android:id="@+id/answerTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp" />
    <Button 
        android:id="@+id/showAnswerButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/show_answer_button"/>

LinearLayout>

land\activity_quiz.xml

"http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    id="@+id/question_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:padding="24dp"
        />
    "wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:orientation="horizontal">
        

你可能感兴趣的:(练习)