[Android / Java] Screen transition and return processing in fragments

Introduction

I'm learning to develop mobile apps using Java in Android Studio. I haven't put much effort into the layout file (roughly). I didn't use the string file because I focused on the screen switching operation.

What I learned

--Switching display fragments using FragmentManager```` FragmentTransaction (screen transition) --`ʻaddToBackStackAction bar using popBackStack`` Back button Click back action

Overview of the sample app created for learning

A simple app that allows you to prepare the main fragment for one activity and switch between the two fragments by pressing a button from there. Activity: 1 Fragment: 3 (1 main, 2 sub)

Click these ① and ② buttons to transition to subfragment 1 and subfragment 2, respectively.

Main screen (MainFragment)
Sub1 screen (SubFragment1)
Sub2 screen (SubFragment2)

Directory structure

スクリーンショット 2020-09-29 15.06.37.png

Processing contents of each java file

File code and description

Describe the code of each file

layout file

activity_main.xml



<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activityMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

</FrameLayout>

fragment_main.xml


<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fragmentMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="25dp"
        android:text="It's the main fragment"/>

    <Button
        android:id="@+id/bt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="250dp"
        android:layout_marginLeft="70dp"
        android:textSize="25dp"
        android:text="①"/>

    <Button
        android:id="@+id/bt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="250dp"
        android:layout_marginLeft="250dp"
        android:textSize="25dp"
        android:text="②"/>

</FrameLayout>

fragment_sub1.xml



<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/SubFragment1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SubFragment1">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="25dp"
        android:text="It's subfragment 1"/>

</FrameLayout>

fragment_sub2.xml



<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/SubFragment2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SubFragment2">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="25dp"
        android:text="Subfragment 2" />

</FrameLayout>

java file

MainActivity.java

MainActivity.java



public class MainActivity extends AppCompatActivity {

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

        //Call method and display MainFragment by default
        addFragment(new MainFragment());
    }

    //Define a method to display Fragment (pass the Fragment you want to display as an argument)
    private void addFragment(Fragment fragment) {
        //Get Fragment Manager
        FragmentManager manager = getSupportFragmentManager();
        //Start of fragment transaction
        FragmentTransaction transaction = manager.beginTransaction();
        //Added Main Fragment
        transaction.add(R.id.activityMain, fragment);
        //Fragment transaction commit. The state of Fragment is reflected by committing
        transaction.commit();
    }

    //Define a method to set the back button "←" to the action bar (upper bar)
    public void setupBackButton(boolean enableBackButton) {
        //Get action bar
        ActionBar actionBar = getSupportActionBar();
        //Set the button "←" to return to the action bar (argument is true):Display, false:Hidden)
        actionBar.setDisplayHomeAsUpEnabled(enableBackButton);
    }
}

I want to display the specified fragment on the screen display, so do transaction.add

Enter such a value as an argument

transaction.add (R value of the layout screen part to be added, Fragment object to be added (want to display));

MainFragment.java

MainFragment.java



public class MainFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Inflate the screen displayed as a fragment from the layout file
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        //Get the parent activity to which you belong
        MainActivity activity = (MainActivity) getActivity();
        //Set the title on the action bar
        activity.setTitle("Main fragment");
        //Hide the back button (Main Fragment does not require a back button)
        //If you do not set this to false, the back button will remain displayed when returning from the subfragment.
        activity.setupBackButton(false);

        //Get button element
        Button bt1 = view.findViewById(R.id.bt1);
        Button bt2 = view.findViewById(R.id.bt2);

        //① Processing when the button is clicked
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Transition to SubFragment1
                replaceFragment(new SubFragment1());
            }
        });

        //② Processing when the button is clicked
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Transition to SubFragment2
                replaceFragment(new SubFragment2());
            }
        });

        return view;
    }

    //Define a method to switch the Fragment to be displayed (pass the Fragment you want to display as an argument)
    private void replaceFragment(Fragment fragment) {
        //Get Fragment Manager
        FragmentManager manager = getFragmentManager(); //GetSupportFragmentManager in activity()?
        //Start of fragment transaction
        FragmentTransaction transaction = manager.beginTransaction();
        //Replaced layout with fragment (added)
        transaction.replace(R.id.activityMain, fragment);
        //Save the replacement transaction on the back stack
        transaction.addToBackStack(null);
        //Commit fragment transaction
        transaction.commit();
    }
}

I have already displayed the main fragment and want to switch the display with the click of a button, so use transaction.replace The argument is the same image as the processing of `ʻadd transaction.replace (R value of the layout screen part to be displayed, Fragment object to be replaced (want to display)); ``

For subfragments that have transitioned from the main fragment, we want to be able to return to the main fragment with the back button "←" on the action bar. transaction.addToBackStack(null); By describing, the fragment displayed before the transition is saved. With this description, in the transition destination fragment getFragmentManager().popBackStack(); By calling, you will be able to return when you click the back button "←"

SubFragment1.java / SubFragment2.java

SubFragment1.java



public class SubFragment1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Inflate the screen displayed as a fragment from the layout file
        View view = inflater.inflate(R.layout.fragment_sub1, container, false);

        //Get Affiliated Parent Activity
        MainActivity activity = (MainActivity) getActivity();
        //Set the title on the action bar
        activity.setTitle("Subfragment 1");
        //Show back button
        activity.setupBackButton(true);

        //With this description, the action bar menu can be used in the fragment.
        setHasOptionsMenu(true);

        return view;
    }

    //Processing when the action bar button is pressed
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            // android.R.id.Detects the operation when the back button "←" is pressed at home
            case android.R.id.home:
                //Executes the process to return to the Fragment displayed before the transition
                getFragmentManager().popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

SubFragment2.java



public class SubFragment2 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Inflate the screen displayed as a fragment from the layout file
        View view = inflater.inflate(R.layout.fragment_sub2, container, false);

        //Get Affiliated Parent Activity
        MainActivity activity = (MainActivity) getActivity();
        //Set the title on the action bar
        activity.setTitle("Subfragment 2");
        //Show back button
        activity.setupBackButton(true);

        //With this description, the action bar menu can be used in the fragment.
        setHasOptionsMenu(true);

        //View view is good?
        return view;
    }

    //Processing when the button on the action bar is pressed
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            //When the back button "←" is pressed android.R.id.The value is entered in home
            case android.R.id.home:
                //Executes the process to return to the Fragment displayed before the transition
                getFragmentManager().popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

getFragmentManager (). PopBackStack (); This description returns to the previous fragment.

Finally

I did not include it in the content this time, but I hope I can write about the transfer of data between fragments in the future.

I'm a beginner for less than a month after learning Java / Android. If you have any suggestions, please comment.

Materials that I used as a reference

It was very easy to understand and was helpful! Thank you very much!

Recommended Posts

[Android / Java] Screen transition and return processing in fragments
Screen transition by [Android Studio] [Java] button
Java to C and C to Java in Android Studio
Parallel and parallel processing in various languages (Java edition)
Represents "next day" and "previous day" in Java / Android
Asynchronous processing and Web API integration in Android Studio
Android development ~ Screen transition (intent) ~
Measured parallel processing in Java
Screen transition with swing, java
JSON in Java and Jackson Part 1 Return JSON from the server
Technical causes and countermeasures for points addicted to Android apps & Kotlin (1. Android screen transition (fragment) processing)
Try implementing Android Hilt in Java
Screen transition using Intent in Kotlin
Encoding and Decoding example in Java
Date processing in Java (LocalDate: Initialization)
I want to return to the previous screen with kotlin and java!
[Java] Loop processing and multiplication table
Screen transition by Post method [Java]
Java arguments, return values and overloads
[Java Swing] Screen transition by CardLayout
Run node.js from android java (processing)
StringBuffer and StringBuilder Class in Java
Support for IllegalArgumentException: No view found for id in fragments in Android Java
Understanding equals and hashCode in Java
About file copy processing in Java
[Android] Convert Map to JSON using GSON in Kotlin and Java
Notes on Android (java) thread processing
[Java] Exception types and basic processing
Hello world in Java and Gradle
[Android] Difference between finish (); and return;
Web application structure by Java and processing flow in the presentation layer
Activity transition with JAVA class refactoring and instance experimented on Android side
Difference between final and Immutable in Java
[Java] for Each and sorted in Lambda
About UI thread processing in Android asynchronous
Arrylist and linked list difference in java
Program PDF headers and footers in Java
Learn Flyweight patterns and ConcurrentHashMap in Java
Java Direction in C ++ Design and Evolution
Reading and writing gzip files in Java
Difference between int and Integer in Java
Discrimination of Enums in Java 7 and above
Create KeyStore and sign apk in processing (android mode) (java can be used if some changes are made)
NLP4J [004] Try text analysis using natural language processing and parsing statistical processing in Java
Impressions and doubts about using java for the first time in Android Studio
NLP4J [003] Try text analysis using natural language processing and part-speech statistical processing in Java
Regarding the transient modifier and serialization in Java
Create barcodes and QR codes in Java PDF
Detect similar videos in Java and OpenCV rev.2
Vulnerabilities and Countermeasures in Important Processing (Purchase Processing) (CSRF)
[Android / Java] Operate a local database in Room
Difference between next () and nextLine () in Java Scanner
Differences in writing Java, C # and Javascript classes
[Processing x Java] Data type and object-oriented programming
[Android] Alphabet uppercase limit and length limit in EditText
Capture and save from selenium installation in Java
Detect similar videos in Java and OpenCV rev.3
Add, read, and delete Excel comments in Java
Check static and public behavior in Java methods
[Java] Understand in 10 minutes! Associative array and HashMap
Basics of threads and Callable in Java [Beginner]