I'm developing an app in Android Studio (java) There was a scene where "I want to call back the button click event of the dialog and process it with the calling fragment". To be more specific, when I implemented API communication + screen transition processing in the dialog, I implemented a callback because the screen transition could not be done probably because the thread was different. I got an error like this `ʻAndroid IllegalStateException: fragment not attached to activity``
So I was able to realize the processing using the callback, so I will write what I learned at that time.
Display a fragment with a button in the activity, and press the button to display a dialog. Press the dialog OK button to change the button text. Just a simple app
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:id="@+id/layout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/fragment_sample"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_sample.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/layout_sample"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SampleFragment">
<Button
android:id="@+id/bt_show_dialog"
android:layout_width="142dp"
android:layout_height="96dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:text="Dialog display"/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set fragment in Activity
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_sample, new SampleFragment())
.commit();
}
}
** * The parts that are called after pressing the button are listed in the order in which they are called **
SampleFragment.java
//Implements to implement the interface
public class SampleFragment extends Fragment implements SampleDialogFragment.SampleDialogListener {
//Define the button element of the dialog display as a global variable
private Button button;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sample, container, false);
//Set the title on the action bar
MainActivity activity = (MainActivity) getActivity();
activity.setTitle("Dialog callback sample");
//Get button elements from layout
button = view.findViewById(R.id.bt_show_dialog);
//Processing when the button is clicked ・ ・ ・ ①
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Get Fragment Manager
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
//Create an instance object of SampleDialogFragment
SampleDialogFragment dialogFragment = SampleDialogFragment.newInstance();
//Set the calling SampleFragment object to the SampleDialogFragment object
dialogFragment.setTargetFragment(SampleFragment.this, 0);
//Show dialog
dialogFragment.show(fragmentManager, "");
}
});
return view;
}
//Process that is called back and executed ... ⑤
@Override
public void onDialogPositiveClick(DialogFragment dialog) {
//Change the characters displayed on the button
button.setText("Callback success");
}
}
SampleDialogFragment.java
public class SampleDialogFragment extends DialogFragment {
//Method to create an instance
public static SampleDialogFragment newInstance() {
return new SampleDialogFragment();
}
//Implemented interface to receive event callback
public interface SampleDialogListener {
void onDialogPositiveClick(DialogFragment dialog);
}
//Define an interface instance to use to signal click event firing
private SampleDialogListener listener;
// onAttach()Verify that the calling parent fragment implements the interface
// onAttach():The first method called in the fragment life cycle,
//Called only once when a fragment is associated with an activity. The context contains the parent activity ... ②
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
//Get the calling SampleFragment object so that you can send the event to the parent fragment
//Create an instance of listener
listener = (SampleDialogListener) getTargetFragment();
} catch (ClassCastException e) {
//Throw an exception if the parent fragment does not implement the interface
throw new ClassCastException(getTargetFragment().toString() + "Does not implement the interface");
}
}
//Generate dialog onCreateDialog
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Generate a dialog ... ③
return new AlertDialog.Builder(getActivity())
.setTitle("Verification")
.setMessage("Do you want to start a callback?")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Call back the process to the parent fragment ... ④
listener.onDialogPositiveClick(SampleDialogFragment.this);
}
})
.setNegativeButton("Cancel", null) // Cancelボタンでは何もしないためnull
.create();
}
}
I haven't understood much yet, but I learned a lot. I would appreciate it if you could comment on any mistakes.
It was very helpful! Thank you very much!
Android developers Dialog Fragment and Fragment Callback Relationship
Recommended Posts