父Activity启动子Activity,并且向其传递消息,子Activity启动后完成相应的操作后回馈父Activity消息,父Activity完成相应的操作。
The simplest way one activity can start another is with the Activity method:
public void startActivity(Intent intent);
An intent is an object that a component can use to communicate with the OS. The only components you have seen so far are activites, but there are services, broadcast receivers, and content providers.
To Inform the CheatActivity of the answer to the current question, you will pass it the value of
mQuestionBank[mCurrentIndex].isAnswerTrue()
You will send this value as an extra on the Intent that is passed into startActivity(Intent).
To add an extra to an intent, you use Intent.putExtra(...). In particular, you will be calling
public Intent putExtra(String name, boolean value)
When you want to hear back from the child activity, you call the following Activity method:
public void startActivityForResult(Intent intent, int requestCode)
The first parameter is the same intent as before. The second parameter is the request code.
strings.xml
<resources>
<string name="app_name">GeoQuiz</string>
<string name="question_text">
Constantinople is the largest city in Turkey.
</string>
<string name="true_button">True</string>
<string name="false_button">False</string>
<string name="correct_toast">Correct!</string>
<string name="incorrect_toast">Incorrect!</string>
<string name="action_settings">Settings</string>
<string name="next_button">Next</string>
<string name="question_oceans">The Pacific Ocean is larger than the Atlantic Ocean.</string>
<string name="question_mideast">The Suez Canal connects the Red Sea and the Indian Ocean.</string>
<string name="question_africa">The source of the Nile River is in Egypt.</string>
<string name="question_americas">The Amazon River is the longest river in the Americas.</string>
<string name="question_asia">Lake Baikal is the world\'s oldest and deepest freshwater lake.</string>
<string name="warning_text">Are you sure you want to do this?</string>
<string name="show_answer_button">Show Answer</string>
<string name="cheat_button">Cheat!</string>
<string name="judgment_toast">Cheating is wrong.</string>
<string name="title_activity_cheat">Cheat</string>
</resources>
activity_quiz.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/question_test_view"
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/true_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:layout_gravity="bottom|center"
android:text="@string/cheat_button"/>
<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>
QuizActivity.java
activity_cheat.xmlpackage com.android.testrecord; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; public class QuizActivity extends AppCompatActivity { private static final String TAG = "QuizActivity"; private static final String KEY_INDEX = "index"; private static final int REQUEST_CODE_CHEAT = 0; private Button mTrueButton; private Button mFalseButton; private Button mNextButton; private Button mCheatButton; private TextView mQuestionTextView; private Question[] mQuestionBank = new Question[]{ new Question(R.string.question_oceans, true), new Question(R.string.question_mideast, false), new Question(R.string.question_africa, false), new Question(R.string.question_americas, true), new Question(R.string.question_asia, true), }; private int mCurrentIndex = 0; private boolean mIsCheater; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient mClient; private void updateQuestion() { int question = mQuestionBank[mCurrentIndex].getTextResId(); mQuestionTextView.setText(question); } private void checkAnswer(boolean userProessedTrue) { boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue(); int messageId = 0; if (mIsCheater) { messageId = R.string.judgment_toast; } else { if (userProessedTrue == answerIsTrue) messageId = R.string.correct_toast; else messageId = R.string.incorrect_toast; } Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0); Log.d(TAG, "onCreate(Bundle) called"); setContentView(R.layout.activity_quiz); mQuestionTextView = (TextView) findViewById(R.id.question_test_view); // int question = mQuestionBank[mCurrentIndex].getTextResId(); // mQuestionTextView.setText(question); updateQuestion(); mTrueButton = (Button) findViewById(R.id.true_button); mTrueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Does nothing yet, but soon! /* Toast.makeText(QuizActivity.this, R.string.incorrect_toast, Toast.LENGTH_SHORT).show(); */ checkAnswer(true); } }); mFalseButton = (Button) findViewById(R.id.false_button); mFalseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Does nothing yet, but soon! /* Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT).show(); */ checkAnswer(false); } }); mNextButton = (Button) findViewById(R.id.next_button); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length; // int question = mQuestionBank[mCurrentIndex].getTextResId(); // mQuestionTextView.setText(question); mIsCheater = false; updateQuestion(); } }); mCheatButton = (Button) findViewById(R.id.cheat_button); mCheatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Start CheatActivity // Intent i = new Intent(QuizActivity.this, CheatActivity.class); boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue(); Intent i = CheatActivity.newIntent(QuizActivity.this, answerIsTrue); // startActivity(i); startActivityForResult(i, REQUEST_CODE_CHEAT); } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK) return ; if (requestCode == REQUEST_CODE_CHEAT) { if (data == null) { return; } mIsCheater = CheatActivity.wasAnswerShown(data); } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); Log.i(TAG, "onSaveInstanceState"); savedInstanceState.putInt(KEY_INDEX, mCurrentIndex); } @Override public void onStart() { super.onStart(); Log.d(TAG, "onStart() called"); } @Override public void onPause() { super.onPause(); Log.d(TAG, "onPause() called"); } @Override public void onStop() { super.onStop(); Log.d(TAG, "onStop() called"); } @Override public void onResume() { super.onResume(); Log.d(TAG, "onResume() called"); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestory() called"); } }
CheatActivity.java<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" tools:context="com.android.testrecord.CheatActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="24dp" android:text="@string/warning_text"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/answer_text_view" android:padding="24dp" android:text="Answer"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/show_answer_button" android:text="@string/show_answer_button"/> </LinearLayout>
输出:package com.android.testrecord; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.TextView; public class CheatActivity extends AppCompatActivity { private static final String EXTRA_ANSWER_IS_TRUE = "com.android.testrecord.geoquiz.answer_is_true"; private static final String EXTRA_ANSWER_SHOWN = "com.android.testrecord.geoquiz.answer_shown"; private boolean mAnswerIsTrue; private TextView mAnswerTextView; private Button mShowAnswer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cheat); mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false); mAnswerTextView = (TextView) findViewById(R.id.answer_text_view); mShowAnswer = (Button) findViewById(R.id.show_answer_button); mShowAnswer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mAnswerIsTrue) { mAnswerTextView.setText(R.string.true_button); } else { mAnswerTextView.setText(R.string.false_button); } setAnswerShowResult(true); } }); } private void setAnswerShowResult(boolean isAnswerShown) { Intent data = new Intent(); data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown); setResult(RESULT_OK, data); } public static Intent newIntent(Context packageContext, boolean answerIsTrue) { Intent i = new Intent(packageContext, CheatActivity.class); i.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue); return i; } public static boolean wasAnswerShown(Intent result) { return result.getBooleanExtra(EXTRA_ANSWER_SHOWN, false); } }