[Android Studio] Fragmentで作成した値をActivityに返す

実行環境:Android Studio 3.6 / JAVA

これまで紹介してきたProjectの完成形です。以下の動画のような動きになります。

https://lifeprosper.link/biz/wp-content/uploads/2020/02/und.webm
  • MainActivityから画面遷移したSubActivityでFragmentを呼びだす
  • 各Fragmentで取得した値はSubActivityを通してMainActivityに戻す
  • MainActivityの意図したTextViewにそれぞれの値が格納されるようにする
  • Android StudioのChipやSeekbarを使う

前回のFragment内でEditTextとSeekBarの使い方から追加したのは以下のセッターだけ。

SubActivity.java

public static void setNumbers(String s){
powerNumb = s;
}

KokyuFragment.java と CosmoFragment.java

 SubActivity.setNumbers(...); 

とりあえず動いた感が否めないですが、これが今の私の精一杯。精進してまいります。以下がこのProjectに関する記事です。

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/amtxt_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:text="Setup attack power"
android:textSize="30sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/amtxt_tanji"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_marginStart="24dp"
android:layout_marginTop="32dp"
android:text="竈門炭治郎"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/amtxt_title" />

<TextView
android:id="@+id/amtxt_shaka"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_marginStart="24dp"
android:layout_marginTop="32dp"
android:text="バルゴのシャカ"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/amtxt_tanji_param" />

<TextView
android:id="@+id/amtxt_tanji_param"
android:layout_width="300dp"
android:layout_height="35dp"
android:layout_marginStart="24dp"
android:layout_marginTop="8dp"
android:gravity="center"
android:textSize="24sp"
android:background="@drawable/text_frame"
android:text="00000"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/amtxt_tanji" />

<TextView
android:id="@+id/amtxt_shaka_param"
android:layout_width="300dp"
android:layout_height="35dp"
android:layout_marginStart="24dp"
android:layout_marginTop="8dp"
android:background="@drawable/text_frame"
android:gravity="center"
android:text="00000"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/amtxt_shaka" />

<Button
android:id="@+id/ambut_tanji"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_marginStart="8dp"
android:layout_marginTop="32dp"
android:gravity="center"
android:text="Setup"
app:layout_constraintStart_toEndOf="@+id/amtxt_tanji"
app:layout_constraintTop_toBottomOf="@+id/amtxt_title" />

<Button
android:id="@+id/ambut_shaka"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_marginStart="8dp"
android:layout_marginTop="32dp"
android:gravity="center"
android:text="Setup"
app:layout_constraintStart_toEndOf="@+id/amtxt_shaka"
app:layout_constraintTop_toBottomOf="@+id/amtxt_tanji_param" />

<TextView
android:id="@+id/satxt_page"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:textSize="20dp"
android:text="Main Activity"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/amtxt_shaka_param" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity_sub.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e6b8c2"
tools:context=".MainActivity">

<FrameLayout
android:id="@+id/container1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="100dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/sabut_register"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/satxt_title" />

<com.google.android.material.chip.ChipGroup
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:clickable="false"
app:layout_constraintBottom_toTopOf="@+id/container1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/satxt_title"
app:singleSelection="true">

<com.google.android.material.chip.Chip
android:id="@+id/chip_kokyu"
style="@style/Widget.MaterialComponents.Chip.Choice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="パワー:呼吸"
android:textAppearance="?android:attr/textAppearanceMedium" />

<com.google.android.material.chip.Chip
android:id="@+id/chip_cosmo"
style="@style/Widget.MaterialComponents.Chip.Choice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="パワー:コスモ"
android:textAppearance="?android:attr/textAppearanceMedium" />
</com.google.android.material.chip.ChipGroup>

<Button
android:id="@+id/sabut_register"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_marginEnd="36dp"
android:layout_marginBottom="32dp"
android:text="Register"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<TextView
android:id="@+id/satxt_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:textSize="20dp"
android:text="パワー種類の選択"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/satxt_page"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginBottom="32dp"
android:text="Sub Activity"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<TextView
android:id="@+id/satxt_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:text="000"
app:layout_constraintStart_toEndOf="@+id/satxt_title"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

kokyu_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#a2bd95"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="20dp"
android:text="KokyuFragment"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:text="Kokyuパワー"
android:textSize="20dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button5" />

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Power値を入力"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:text="Set"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />

</androidx.constraintlayout.widget.ConstraintLayout>

cosmo_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fde4a0"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="20dp"
android:text="CosmoFragment"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<SeekBar
android:id="@+id/seekBar"
android:layout_width="260dp"
android:layout_height="29dp"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:max="9999"
android:progress="5000"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:text="Cosmoパワー"
android:textSize="20dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/seekBar" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.example.sampleattack;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public static final String MAIN_KEY = "MAIN_KEY";
static final int MAIN_S = 100;

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

Button sendButton1 = findViewById(R.id.ambut_tanji);
sendButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), SubActivity.class);
int e = 1;
intent.putExtra(MAIN_KEY, e);
startActivityForResult(intent, MAIN_S);
}
});
Button sendButton2 = findViewById(R.id.ambut_shaka);
sendButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), SubActivity.class);
int e = 2;
intent.putExtra(MAIN_KEY, e);
startActivityForResult(intent, MAIN_S);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);

if (resultCode == RESULT_OK && requestCode == MAIN_S && null != intent) {
int key = intent.getIntExtra(SubActivity.SUB_KEY, 0);
switch (key) {
case 1:
TextView textView1 = findViewById(R.id.amtxt_tanji_param);
String res1 = intent.getStringExtra(SubActivity.SUB_KEY2);
textView1.setText(res1);
break;
case 2:
TextView textView2 = findViewById(R.id.amtxt_shaka_param);
String res2 = intent.getStringExtra(SubActivity.SUB_KEY2);
textView2.setText(res2);
break;
}
}
}
}

SubActivity.java

package com.example.sampleattack;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.material.chip.Chip;

public class SubActivity extends AppCompatActivity {
public static final String SUB_KEY = "SUB_KEY";
public static final String SUB_KEY2 = "SUB_KEY2";
private int key;
private static String powerNumb;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);

Chip chipKokyu = findViewById(R.id.chip_kokyu);
chipKokyu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.container1, new KokyuFragment());
fragmentTransaction.commit();
}
});

Chip chipCosmo = findViewById(R.id.chip_cosmo);
chipCosmo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.container1, new CosmoFragment());
fragmentTransaction.commit();
}
});

Intent intent = getIntent();
key = intent.getIntExtra(MainActivity.MAIN_KEY,0);
String testtxt = String.valueOf(key);
TextView textView = findViewById(R.id.satxt_test);
textView.setText(testtxt);

Button returnButton = findViewById(R.id.sabut_register);
returnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
String power = powerNumb;
intent.putExtra(SUB_KEY, key);
intent.putExtra(SUB_KEY2, power);
setResult(RESULT_OK, intent);
finish();
}
});
}
public static void setNumbers(String s){
powerNumb = s;
}
}

KokyuFragment.java

package com.example.sampleattack;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

public class KokyuFragment extends Fragment{
    EditText editText5;
    TextView textView;
    Button button5;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.kokyu_fragment, container, false);
    }
    @Override
    public void onStart(){
        super.onStart();
        findViews();

        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = editText5.getText().toString();
                String powerKokyu = "Kokyuパワー:"+text;
                textView.setText(powerKokyu);
                SubActivity.setNumbers(powerKokyu);
            }
        });
    }
    protected void findViews() {
        editText5 = (EditText) getActivity().findViewById(R.id.editText);
        textView = (TextView) getActivity().findViewById(R.id.textView5);
        button5 = (Button) getActivity().findViewById(R.id.button5);
    }
}

CosmoFragment.java

package com.example.sampleattack;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

public class CosmoFragment extends Fragment {
SeekBar seekbar;
TextView textView;
private static int power;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.cosmo_fragment, container, false);
}
@Override
public void onStart(){
super.onStart();
findViews();
seekbar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar,int progress, boolean fromUser) {
textView.setText("Cosmoパワー:"+seekBar.getProgress());
}
public void onStartTrackingTouch(SeekBar seekBar) {}

public void onStopTrackingTouch(SeekBar seekBar) {
power = seekBar.getProgress();
String powerNumb = "Cosmoパワー:"+power;
textView.setText(powerNumb);
SubActivity.setNumbers(powerNumb);
}
}
);
}
protected void findViews() {
seekbar = (SeekBar) getActivity().findViewById(R.id.seekBar);
textView = (TextView) getActivity().findViewById(R.id.textView2);
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sampleattack">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SubActivity"
android:label="@string/app_name">
</activity>
</application>

</manifest>