訓練68日目【Androidアプリ作成3】計算結果を別画面に表示する | 半年間でAndroidアプリを自力で作れるよーになりたーい! 

訓練68日目【Androidアプリ作成3】計算結果を別画面に表示する

BMI(ボディ・マス指数)計算する簡単なサンプルプログラムを作っています。


さて、前日に引き続き、Androidアプリ開発の練習です。 が! 今日からは

アクティビティの勉強ではなく、インテントの勉強の中で作っています。


このアプリを作るだけじゃなくって、インテントの意味や、コンフィグレーションの変更の

種類なども勉強したんですがね。。。 まぁ、これも追々でいいような気がします。

つーか、このテキスト本、話が色々飛びすぎて、わかりずらいよぉーショック!



気を取り直して、今日はページ110にある「計算結果を別画面に表示する」に挑戦です。


半年間でAndroidアプリを自力で作れるよーになりたーい! -BMI2_1

前との違いは・・・ 「結果を次の画面に表示」というボタンが増えたこと!

さらにこのボタンを押してみると・・・↓↓↓


半年間でAndroidアプリを自力で作れるよーになりたーい! -BMI2_2
新しい画面が表示され、そちらに結果が表示されます。


これを実現させるため、新たに出てきたコーディングは・・・


putExtraメソッド

startActivityForResultメソッド


ですが、javaのコーディングより、もっとも大事なインテントの基本的な使い方を知るための

最初の1歩なので、xmlファイルの追加修正もあわせて、大まかな作業の流れを下記にまず

は記述します。


文末は、実際にeclipseで書いたコーディングです。もちろん、そのままコピペしたら動くはず。

ココアのブログは、普通の人は、黒文字だけ読んで、青文字は読み飛ばしてOKなので。

1と2から大幅に書き方を変えて申し訳ありませんが、これまたご了承ください。。。。ぶーぶー


★手順のポイント★

=============

1)string.xmlでリソースを定義します。

<string name="button_show_next_activity">結果を次画面に表示</string>

2)main.xmlでレイアウトを修正します。

<Button
android:id="@+id/button_show_next_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_show_next_activity" />


3)今回新たに作成する結果表示用アクテイビテイが利用するレイアウトを定義します。

res/layout下に、result.xmlというファイルを新たに作成し、以下のように定義します。

<TextView
android:id="@+id/label_bmivalue"

TextViewであっても、例のように「android:id」を設定することで、プログラムから文字列を設定
することができるようになります。ここでは、BMIの値と、その判定結果(太りすぎ、痩せすぎ、標
準体型)などを表示する項目に対してそれぞれIDを付加しています。


4)結果表示用のアクティビティ(ResultActivity.java)の作成。
コーディングに入ります。まず、「ResultActivity」という名称でJavaファイルを新規作成し、
結果を表示するアクテイビテイを定義します。ファイルを作成する場所は、入力用アクテイビテイ
(BMICalculatorActivity)と同一のパッケージ(com.mamezou.android.bmicalc)にしてください。

public class ResultActivity extends Activity {

①名前はResultActivityとします。
Bundle extras = getIntent().getExtras();

②インテントから付加情報を取得します。
height = extras.getInt("HEIGHT");

③前のアクティビテイから渡された入力値(身長、体重)を付加情報より取得します。

if (bmi > 24)

④BMIの計算を行い、判定結果(太りすぎ、痩せすぎ、標準体型)をウイジェットに設定します。
ここでは、BMIが18未満であれば「痩せすぎ」、24よりも大きければ「太りすぎ」、18以上24以
下であれば「標準体型」としています。


5)入力用アクテイビテイ(BMICalculatorActivity)の修正

次に、前章「第2部第2章アクテイビテイ」で作成したBMICalculatorActivityを以下のように
拡張します。

buttonShowNextActivity.setOnClickListener(new View.OnClickListener() {
①新たに追加したボタンに対するイベントリスナを実装します。このボタンが押されたときに、結
果表示用の画面が表示されるようにします。

Intent intent = new Intent(BMICalculatorActivity.this, ResultActivity.class);

②インテントのインスタンスを生成します。ここでは、元画面のアクテイビテイのインスタンスと、
次画面のアクテイビテイのクラスを明示的に指定しています。次画面のクラス名には先ほど作成
したResultActivityを指定します。
intent.putExtra("HEIGHT", Integer.parseInt(textHeight.getText().toString()));

③インテントのputExtraメソッドを使って、入力された「身長」と「体重」の値を付加情報に登録し
ます。ここで登録したものは、インテントを受け取った次画面で自由に参照することができます。
付加情報は、文字列をキーとしたMapとして保持されているため、キーとなる文字列("HEIGHT"
や"WEIGHT")と値のペアで設定しています。

startActivityForResult(intent, 0);
startActivityForResultメソッドを使ってResultActivityを起動します。ここで起動される
アクテイビテイや、そのアクテイビテイに渡される情報はstartActivityForResultメソッドに
渡されたインテントの内容によって決まります。2番目の引数として「0」を渡しています。これ
はリクエストコードと呼びます。リクエストコードは、再び親のアクテイビテイへ戻ってきたと
きに、どのアクテイビテイから戻ってきたのかを区別するための値で、0以上の数値を指定しま
す。(リクエストコードに負の値を設定すると、このメソッドによって起動されたアクテイビテイから

の結果を受け取ることはできません。つまりstartActivityメソッドを使ったのと同じふるまいに

なります)


6)マニフェストファイルの定義
最後に、新たに作成したアクテイビテイをマニフェストファイル(AndroidManifest.xml)に追記
します。

<activity android:name=".ResultActivity" android:label="@string/app_name" />
①今回作成したResultActivityを追記します。追記することで、ResultActivityクラスがアプリ
ケーション内のアクテイビティとして認識されるようになります。その他の箇所は変更する必要
はありません。

=============


上記の流れに従って、、、 以下は実際のeclipse画面。
半年間でAndroidアプリを自力で作れるよーになりたーい! -BMICal2

↓ここからは、実際に書いたコーディングになります。↓


まず、string.xmlに「結果を次の画面に表示」という表示されるメッセージを追加します。

「文字列定数を追加する」といいます。


▼string.xml

====

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">BMI Calculator</string>
<string name="label_description">BMIを計算します</string>
<string name="label_height">身長(cm)</string>
<string name="label_weight">体重(kg)</string>
<string name="button_calculate">計算</string>
<string name="button_close_dialog">閉じる</string>
<string name="label_bmi_description">あなたのBMIは</string>
<string name="button_show_next_activity">結果を次画面に表示</string>
<string name="label_too_slim">痩せ気味です</string>
<string name="label_standard">標準体型です</string>
<string name="label_too_fat">太り気味です</string>
</resources>
====

これをテキスト画面で入力した後、リソースタブを押したら、こんな画面になりました。


半年間でAndroidアプリを自力で作れるよーになりたーい! -BMI2_3
つまり、次は、main.xmlでボタンを追加しなきゃです。


▼main.xml

====

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android "
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/label_description"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/label_height"
/>
<EditText android:id="@+id/text_height"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numeric="integer"
android:maxLength="3"
android:text="160"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/label_weight"
/>
<EditText android:id="@+id/text_weight"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numeric="integer"
android:maxLength="3"
android:text="50"
/>
<Button
android:id="@+id/button_calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_calculate" />
<Button
android:id="@+id/button_show_next_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_show_next_activity" />
</LinearLayout>

====

そして次画面用のレアウトを定義するので、新しくresult.xmlを作ります。

main.xmlと同じ、layoutのフォルダー下に作ります。


▼result.xml

====

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android "
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/label_bmi_description"
/>
<TextView
android:id="@+id/label_bmivalue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/label_status"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

====


さぁ、ここから下はコーディングです。

ResultActivity.javaという新しいクラスを作ります。


▼ResultActivity.java

====

package com.mamezou.android.bmicalc;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ResultActivity extends Activity {
private int height = 0;
private int weight = 0;
private int bmi = 0;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.result);
TextView bmiValue = (TextView) findViewById(R.id.label_bmivalue);
TextView status = (TextView) findViewById(R.id.label_status);
Bundle extras = getIntent().getExtras();
if (extras != null) {
height = extras.getInt("HEIGHT");
weight = extras.getInt("WEIGHT");
bmi = 10000 * weight / height / height;
bmiValue.setText(String.valueOf(bmi));
if (bmi > 24)
status.setText(R.string.label_too_fat);
else if (bmi < 18)
status.setText(R.string.label_too_slim);
else
status.setText(R.string.label_standard);
}
}
}

====


さらに、BMICalculatorActivity.javaに追記します。


▼BMICalculatorActivity.java

====

package com.mamezou.android.bmicalc;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class BMICalculatorActivity extends Activity {
private EditText textHeight;
private EditText textWeight;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.v("EXAMPLE", "onCreate was called.");
setContentView(R.layout.main);
textHeight = (EditText) findViewById(R.id.text_height);
textWeight = (EditText) findViewById(R.id.text_weight);
Button button = (Button) findViewById(R.id.button_calculate);
Button buttonShowNextActivity = (Button) findViewById(R.id.button_show_next_activity);

final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.label_bmi_description);
builder.setPositiveButton(R.string.button_close_dialog, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setResult(RESULT_OK);
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int height = Integer.parseInt(textHeight.getText().toString());
int weight = Integer.parseInt(textWeight.getText().toString());
int bmi = 10000 * weight / height / height;
builder.setMessage(String.valueOf(bmi));
builder.create();
builder.show();
}
});
buttonShowNextActivity.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(BMICalculatorActivity.this, ResultActivity.class);
intent.putExtra("HEIGHT", Integer.parseInt(textHeight.getText().toString()));
intent.putExtra("WEIGHT", Integer.parseInt(textWeight.getText().toString()));
startActivityForResult(intent, 0);
}
});
}

@Override
protected void onStart() {
super.onStart();
Log.v("EXAMPLE", "onStart was called.");
}

@Override
protected void onRestart() {
super.onRestart();
Log.v("EXAMPLE", "onRestart was called.");
}

@Override
protected void onResume() {
super.onResume();
Log.v("EXAMPLE", "onResume was called.");
}

@Override
protected void onPause() {
super.onPause();
Log.v("EXAMPLE", "onPause was called.");
}

@Override
protected void onStop() {
super.onStop();
Log.v("EXAMPLE", "onStop was called.");
}

@Override
protected void onDestroy() {
super.onDestroy();
Log.v("EXAMPLE", "onDestroy was called.");
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.v("EXAMPLE", "onConfigurationChanged was called.");
}
}

====


最後に、マニフェストファイルにも追記します。


▼AndroidManifest.xml

====

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android "
package="com.mamezou.android.bmicalc">
<application android:icon="@drawable/icon">
<activity android:name=".BMICalculatorActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ResultActivity" android:label="@string/app_name" />
</application>
</manifest>

====

以上で完成です!!


たった2画面出すだけで、結構な作業量でした。

でも、慣れてきたら、もっとラクに感じるのかなぁ?


Google Androidプログラミング入門/江川 崇
 
¥3,990
Amazon.co.jp
このブログは、Google Androidプログラミング入門のP110~115を参照しています。
ペタしてね