前のレッスンを完了すると、アプリが作成され、アクティビティが表示されます。このアクティビティは、テキスト フィールドと送信ボタンを備えた 1 つの画面で構成されています。このレッスンでは、ユーザーが送信ボタンをタップしたときに、新しいアクティビティを開始してメッセージを表示するコードを MainActivity
に追加します。
送信ボタンに応答する
以下の手順に沿って、送信ボタンがタップされたときに呼び出されるメソッドを MainActivity
クラスに追加します。
app > java > com.example.myfirstapp > MainActivity ファイルで、次の
sendMessage()
メソッドスタブを追加します。Kotlin
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } /** Called when the user taps the Send button */ fun sendMessage(view: View) { // Do something in response to button } }
Java
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** Called when the user taps the Send button */ public void sendMessage(View view) { // Do something in response to button } }
メソッドの引数として使用される
View
クラスを Android Studio が解決できないため、エラーが表示される場合があります。このエラーをクリアするには、View
宣言をクリックし、そこにカーソルを置いて Alt+Enter キー(Mac の場合は Option+Enter キー)を押して、クイック修正を行います。メニューが表示された場合は、[Import class] を選択します。- activity_main.xml ファイルに戻って、ボタンからメソッドを呼び出します。
- Layout Editor でボタンを選択します。
- [Attributes] ウィンドウで [onClick] プロパティを見つけ、プルダウン リストから [sendMessage [MainActivity]] を選択します。
これで、ボタンをタップすると
sendMessage()
メソッドが呼び出されます。このメソッドの詳細に注意してください。この詳細は、メソッドが
android:onClick
属性と互換性があることをシステムで認識するために必要です。具体的には、このメソッドには次のような特性があります。 - 次に、テキスト フィールドのコンテンツを読み込むようにこのメソッドを設定し、そのテキストを別のアクティビティに送ります。
インテントを作成する
Intent
は、異なるコンポーネント(2 つのアクティビティなど)間で実行時バインディングを付与するオブジェクトです。Intent
はアプリの「何かを行うという意図」を表します。インテントは幅広いタスクで使用できますが、このレッスンでは別のアクティビティを開始するために使われます。
次に示すように、MainActivity
で EXTRA_MESSAGE
定数と sendMessage()
のコードを追加します。
Kotlin
const val EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE" class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } /** Called when the user taps the Send button */ fun sendMessage(view: View) { val editText = findViewById<EditText>(R.id.editTextTextPersonName) val message = editText.text.toString() val intent = Intent(this, DisplayMessageActivity::class.java).apply { putExtra(EXTRA_MESSAGE, message) } startActivity(intent) } }
Java
public class MainActivity extends AppCompatActivity { public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** Called when the user taps the Send button */ public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.editTextTextPersonName); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } }
Android Studio で [Cannot resolve symbol] エラーが再度表示されます。エラーをクリアするには、Alt+Enter キー(Mac の場合は Option+Return キー)を押します。インポート内容は次のようになります。
Kotlin
import androidx.appcompat.app.AppCompatActivity import android.content.Intent import android.os.Bundle import android.view.View import android.widget.EditText
Java
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText;
DisplayMessageActivity
のエラーは残っていても問題ありません。これは次のセクションで修正できます。
sendMessage()
で起こっていることを次に示します。
Intent
コンストラクタには、Context
とClass
の 2 つのパラメータがあります。Context
パラメータは、Activity
クラスがContext
のサブクラスであるため、最初に使用されます。アプリ コンポーネントの
Class
パラメータにはIntent,
が指定されます。ここでは開始されるアクティビティです。putExtra()
メソッドはEditText
の値をインテントに追加します。Intent
では、extras という Key-Value ペアでデータ型をやり取りできます。使用するキーは
EXTRA_MESSAGE
というパブリック定数で、次のアクティビティでこのキーを使用してテキスト値を取得します。インテントの extras のキーを接頭語としてアプリのパッケージ名を付けて定義することをおすすめします。これにより、アプリが他のアプリと連携する場合に、キーを一意に識別できるようになります。startActivity()
メソッドは、Intent
で指定されたDisplayMessageActivity
のインスタンスを開始します。次に、そのクラスを作成する必要があります。
2 番目のアクティビティを作成する
2 番目のアクティビティを作成する手順は次のとおりです。
- [Project] ウィンドウで [app] フォルダを右クリックし、[New] > [Activity] > [Empty Activity] を選択します。
- [Configure Activity] ウィンドウの [Activity Name] に「DisplayMessageActivity」と入力します。他のすべてのプロパティはデフォルトのままにして、[Finish] をクリックします。
Android Studio は自動的に次の 3 つの処理を実行します。
DisplayMessageActivity
ファイルを作成します。activity_display_message.xml
レイアウト ファイルを作成します。これはDisplayMessageActivity
ファイルに対応します。- 必要な
<activity>
要素をAndroidManifest.xml
に追加します。
このアプリを実行して 1 つ目のアクティビティでボタンをタップすると、2 つ目のアクティビティが開始されますが、中身は空です。これは、2 つ目のアクティビティが、テンプレートで提供された空のレイアウトを使用しているためです。
テキストビューを追加する

新しいアクティビティには空のレイアウト ファイルが含まれています。次の手順でメッセージが表示される場所にテキストビューを追加します。
- app > res > layout > activity_display_message.xml ファイルを開きます。
- ツールバーの Enable Autoconnection to Parent アイコン
をクリックします。これにより、Autoconnect が有効になります(図 1 を参照)。
- [Pallete] パネルで [Text] をクリックして [TextView] をレイアウトにドラッグし、レイアウトの上部中央付近にドロップして、表示される縦線にスナップします。Autoconnect により、ビューを水平方向の中央に配置する左右の制約が追加されます。
- テキストビューの上部からレイアウトの上部に対して制約をもう 1 つ適用します。これにより、図 1 のように表示されます。
オプションで、[Attributes] ウィンドウの [Common Attributes] パネルで [textAppearance] を展開する場合は、テキスト スタイルを調整し、[textSize] や [textColor] などの属性を変更できます。
メッセージを表示する
次の手順では、1 つ目のアクティビティから渡されたメッセージを表示するように、2 つ目のアクティビティを変更します。
DisplayMessageActivity
で、次のコードをonCreate()
メソッドに追加します。Kotlin
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_display_message) // Get the Intent that started this activity and extract the string val message = intent.getStringExtra(EXTRA_MESSAGE) // Capture the layout's TextView and set the string as its text val textView = findViewById<TextView>(R.id.textView).apply { text = message } }
Java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_message); // Get the Intent that started this activity and extract the string Intent intent = getIntent(); String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); // Capture the layout's TextView and set the string as its text TextView textView = findViewById(R.id.textView); textView.setText(message); }
Alt+Enter(Mac の場合は Option+Return)を押して、他の必要なクラスをインポートします。
Kotlin
import androidx.appcompat.app.AppCompatActivity import android.content.Intent import android.os.Bundle import android.widget.TextView
Java
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView;
上方向へのナビゲーションを追加する
アプリのメインのエントリ ポイントではない各画面、つまりホーム画面ではないすべての画面に、アプリ階層の論理的な親画面にユーザーを誘導するナビゲーションが必要です。そのためには、アプリバーに上方向ボタンを追加します。
上方向ボタンを追加するには、AndroidManifest.xml
ファイルで論理的な親になるアクティビティを宣言する必要があります。app > manifests > AndroidManifest.xml ファイルを開いて DisplayMessageActivity
の <activity>
タグを見つけ、次のように置き換えます。
<activity android:name=".DisplayMessageActivity" android:parentActivityName=".MainActivity"> <!-- The meta-data tag is required if you support API level 15 and lower --> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity>
これで、上方向ボタンが Android システムによってアプリバーに自動的に追加されます。
アプリを実行する
ツールバーの Apply Changes アイコン をクリックして、アプリを実行します。アプリが開いたら、テキスト フィールドにメッセージを入力して [Send] をタップすると、2 つ目のアクティビティにメッセージが表示されます。

これで最初の Android アプリが完成しました。
Android アプリ開発の基本を引き続き学習するには、初めてのアプリを作成するに戻り、記載されている他のリンクをご覧ください。