やりたいこと
Android Studioを使ってJavaでアプリを実装する際。
あるボタンをクリックすると別の画面に遷移する。
そして「戻るボタン」を押すと、元の画面に戻る。
ページ構成
2つのページ「page1.xml」「page2.xml」を作成する。
互いに遷移するボタンを置いて、各IDに「to_page2」「to_page1」を付与する。
わかりやすいように帯の色を変えておく。
1ページ目
page1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3F51B5"
android:text="このページは「page1」です。"
android:textColor="#FFFFFF" />
<Button
android:id="@+id/to_page2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="押したらpage2へ" />
</LinearLayout>
2ページ目
page2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#E91E63"
android:text="このページは「page2」です。"
android:textColor="#FFFFFF" />
<Button
android:id="@+id/to_page1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="押すとpage1へ戻る" />
</LinearLayout>
メイン処理
MainActivity.java を下記のように実装する。
MainActivity.java
package com.example.yamato191019a;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 最初に表示されるページはpage1
setContentView(R.layout.page1);
setToPage2();
}
/**
* 「押すとpage1へ戻る」ボタンが押されたときに、1ページ目を表示する。
*/
protected void setToPage1()
{
Button buttonToPage1 = this.findViewById(R.id.to_page1);
buttonToPage1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
setContentView(R.layout.page1);
setToPage2();
}
});
}
/**
* 「押したらpage2へ」ボタンが押されたときに、2ページ目を表示する。
*/
protected void setToPage2()
{
Button buttonToPage2 = this.findViewById(R.id.to_page2);
buttonToPage2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
setContentView(R.layout.page2);
setToPage1();
}
});
}
}
これにより、ボタンを押すことで相互にページ表示を切り替えられる。