【Android Studio】Kotlinでつくるクイズアプリ講座 第6回「結果画面の作成」

今回はクイズの正解数とトータルスコアを表示する結果画面を作成していきます。

動画
結果画面の作成
1. 結果画面のアクティビティを作成
新しいアクティビティを作成して
- ResultActivity.kt
- activity_result.xml
を用意しましょう。
プロジェクト構造にあるパッケージ名(com.example.quizapp)の上で右クリックして、New → Activity → Empty Views Activity を選択します。

Activity Name に ResultActivity と入力して「Finish」を押します。

ResultActivity.kt と activity_result.xml が作成できたら、結果画面のレイアウトを作成していきましょう。
2. strings.xml の準備
クイズ画面と同じように文字列を strings.xml に用意しておきます。

10〜13行目を追加します。
正解数を「5問中3問正解」と表示したい場合は
<string name="result_score">5問中%d問正解</string>
と書いて下さい。
3. レイアウトを作成
activity_result.xml を開いて以下のコードを書きます。
このような画面になりましたか?

クイズ画面の作成で書いた XML とほとんど同じですが、いくつか要素を見てみましょう。
18〜24行目:TextView
ここにはクイズの正解数を表示します。
26〜32行目:TextView
ここにはクイズの累積正解数(今までに何問正解したか)を表示します。
このトータルスコアはクイズデータとしてアプリに保存されるようにします。
34〜39行目:Button
もう一度クイズに挑戦できるように、クイズ画面にもどるボタンを用意します。
4. 不要なコードの削除
activity_main.xml と同じように、3行目のコードは必要ないので削除しておきましょう。

次に行うこと
これで結果画面のレイアウトは完成です!
次回はクイズ結果を表示して、スコアを保存できるようにしていきます。
ここまでのコード
- strings.xml
-
<resources> <string name="app_name">QuizApp</string> <!-- クイズ画面 --> <string name="question_label">問題文</string> <string name="count_label">Q%d</string> <string name="btn_answer">選択肢</string> <!-- 結果画面 --> <string name="result_title">結果</string> <string name="result_score">%d / 5</string> <string name="result_total_score">トータルスコア : %d</string> <string name="btn_return">もどる</string> </resources>
- activity_result.xml
-
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ResultActivity" android:orientation="vertical" android:gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/result_title" android:textSize="22sp" /> <TextView android:id="@+id/resultLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/result_score" android:textSize="30sp" android:layout_marginTop="60dp" /> <TextView android:id="@+id/totalScoreLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/result_total_score" android:textSize="20sp" android:layout_marginTop="60dp" /> <Button android:id="@+id/returnBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_return" android:layout_marginTop="80dp" /> </LinearLayout>