はじめに
画面遷移をしてみます。
また、遷移前のページで表示した値を遷移後の画面でも表示させてみようと思います。
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で切り替えて、値を渡したほうが良いのでしょうね。
登録前の確認画面としては使えるのではないでしょうか。