LoginSignup
0
1

More than 1 year has passed since last update.

【android】画面遷移について

Last updated at Posted at 2022-10-30

はじめに

画面遷移をしてみます。
また、遷移前のページで表示した値を遷移後の画面でも表示させてみようと思います。

image.png
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
image.png

java

MainActivity.java
package com.example.testapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView txt;
    private TextView nextTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt = (TextView)this.findViewById(R.id.text1);
    }

    //ボタン(こんにちは)
    public void jHelloButton(View view){
        txt.setText(R.string.temp1);
    }

    //ボタン(HELLO)
    public void helloButton(View view){
        txt.setText(R.string.temp2);
    }

    //画面遷移ボタン
    public void nextButton(View view){
        setContentView(R.layout.next);
        nextTxt = (TextView)this.findViewById(R.id.next_text1);
        nextTxt.setText(txt.getText());

    }
}

nextButton()で次の画面(xml)をセットします。
setContentView(R.layout.next);で遷移するページをセットしています。
そのあとに、nextTxt = (TextView)this.findViewById(R.id.next_text1);で遷移先のxmlで定義しているnext_text1というテキストフィールドのプロパティを取得し、値をセットしています。

xml

next.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:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/next_text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

おわりに

Activityの切り替えで値を渡す方法は調べるとwiki等に載っていますが、レイアウトの切り替え時に値を渡す方法が見つからなかったので、試してみました。
詰まりポイントとしては、
setContentView(R.layout.next);で遷移する前に
nextTxt = (TextView)this.findViewById(R.id.next_text1);でテキストフィールドのプロパティを取得しようとしてもエラーになります。
おそらく、this.findViewByIdは遷移後のxmlを示しているようです。
そのため、遷移前に取得しようとすると「そんなID無いよ」と怒られているのだと思います。
定石としては、Activityで切り替えて、値を渡したほうが良いのでしょうね。
登録前の確認画面としては使えるのではないでしょうか。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1