Fragment basics

Verification environment

The content of this article has been verified in the following environment.

What is Fragment

How to create a Fragment

Create a subclass of Fragment like Activity. The Fragment class exists in the android.app package and the android.support.v4.app package, You should use the support v4 Fragment class. The Fragment class that fixes the bug of the Fragment class in the android.app package is stored in support v4.

Life cycle method

Like Activity, there is a life cycle. Life cycle methods are deeply involved in the activity life cycle. The following is the order when Fragment is added by onCreate of Activity. If the fragment tag is described in the layout file of Activity and the complete class name of the fragment class is described in the name attribute, the order is not as follows.

Method for going to the foreground

Method Description
onAttach(Activity)
* API Level 23 or later on Attach(Context)
Method called when associated with an activity
onCreate(Bundle) Method called when generating a fragment
onCreateView(LayoutInflater, ViewGroup, Bundle) Method called when creating View to display in fragment
onActivityCreated(Bundle) Method called when the processing of Activity's onCreate method is completed
onViewStateRestored(Bundle) Method called when restoration of state-saved fragment is complete
onStart() A method that is called after executing the onStart method of Activity and processes the screen display for the user.
onResume() It is called after executing the onResume method of Activity, and waits for an event from the user after the processing is completed.

Method to be in the background

Method Description
onPause() Called just before executing the onPause method of Activity.
onStop() Called just before the Activity's onStop method is executed.
onDestroyView() Called before the Activity's onDestroy method. Method called when cleaning View associated with Fragment
onDestroy() Called before the Activity's onDestroy method. Method called when cleaning the state of Fragment
onDetach() Called before the Activity's onDestroy method. Method called when breaking the connection with Activity

Example app using Fragment

App specifications

An application that prepares a button and when the button is pressed, a Fragment corresponding to the button is generated and replaced.

Complete image

Fragment_01.png

Fragment displayed when the button is pressed

Personal information button

Layout file

fragment_user_info.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="jp.co.casareal.sample.fragmentsample.fragment.UserInfoFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:textSize="20sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Name: Casa Real Taro" />
    <TextView
        android:textSize="20sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Age: 33 years old" />

</LinearLayout>

Java source code

UserInfoFragment.java


package jp.co.casareal.sample.fragmentsample.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import jp.co.casareal.sample.fragmentsample.R;

public class UserInfoFragment extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_user_info, container, false);
    }

}

Favorite color button

Layout file

fragment_color.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="jp.co.casareal.sample.fragmentsample.fragment.ColorFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:textSize="20sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Favorite color: orange" />

</LinearLayout>

Java source code

ColorFragment.java


package jp.co.casareal.sample.fragmentsample.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import jp.co.casareal.sample.fragmentsample.R;

public class ColorFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_color, container, false);
    }
}

Fragment to display 4 buttons

The part that displays the four buttons is also created with Fragmet. As a point here, the method of the character string that was set to the onClick attribute of the Button tag It is a specification that is linked if defined, but the class that implements the method of onClick attribute must be Activity that holds Fragment. </ b> If you implement it with Fragment, you need to get View with findViewById and set it with setOnClickListener without Fragment.

Layout file

fragment_menu.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

        <Button
            android:onClick="onClickUserInfo"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.25"
            android:id="@+id/userInfoButton"
            android:text="@string/btnUserInfo"
            />
        <Button
            android:onClick="onClickColor"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.25"
            android:id="@+id/colorButton"
            android:text="@string/btnColor"
            />


        <Button
            android:onClick="onClickDrink"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.25"
            android:id="@+id/drinkButton"
            android:text="@string/btnDrink"
            />
        <Button
            android:onClick="onClickFood"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.25"
            android:id="@+id/foodButton"
            android:text="@string/btnFood"
            />

</LinearLayout>

Java source code

MenuFragment.java


package jp.co.casareal.sample.fragmentsample.fragment;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import jp.co.casareal.sample.fragmentsample.R;


public class MenuFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       return inflater.inflate(R.layout.fragment_menu, container, false);
    }


}

Activities that make up the entire screen

Fragment tag

Fragment that displays 4 buttons is described by tag and linked with Java by name attribute. The frament displayed when the button is pressed is specified by the id attribute so that it can be replaced dynamically.

Replacing Fragment

Call the beginTransaction () method of the FragmentManager class to get the FragmentTransaction. Fragment is replaced by the replace () method. After setting the Fragment, call the commit () method. Also, if you want to display the previous Fragment when the back button is pressed, you can use the Fragment setting timing. Must be saved on the back stack with the addToBackStack () method.

Layout file

activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="jp.co.casareal.sample.fragmentsample.MainActivity">

    <FrameLayout
        android:id="@+id/menuFrame"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp">

    <fragment
        android:id="@+id/menuFragment"
        android:name="jp.co.casareal.sample.fragmentsample.fragment.MenuFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/fragment_menu"
        />
    </FrameLayout>

    <FrameLayout
        android:id="@+id/contents"
        android:layout_width="368dp"
        android:layout_height="417dp"

        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/menuFrame"
        app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>

Java source code

MainActivity.java


package jp.co.casareal.sample.fragmentsample;




import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import jp.co.casareal.sample.fragmentsample.fragment.ColorFragment;
import jp.co.casareal.sample.fragmentsample.fragment.DrinkFragment;
import jp.co.casareal.sample.fragmentsample.fragment.FoodFragment;
import jp.co.casareal.sample.fragmentsample.fragment.UserInfoFragment;

public class MainActivity extends AppCompatActivity {

    private FragmentManager fragmentManager;

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

    public void onClickUserInfo(View view) {
        Fragment fragment = new UserInfoFragment();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.contents,fragment );
        transaction.addToBackStack(null);
        transaction.commit();
    }

    public void onClickColor(View view) {
        Fragment fragment = new ColorFragment();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.contents,fragment );
        transaction.addToBackStack(null);
        transaction.commit();
    }

    public void onClickDrink(View view) {
        Fragment fragment = new DrinkFragment();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.contents,fragment );
        transaction.addToBackStack(null);
        transaction.commit();

    }

    public void onClickFood(View view) {
        Fragment fragment = new FoodFragment();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.contents,fragment );
        transaction.addToBackStack(null);
        transaction.commit();
    }
}


reference

https://developer.android.com/guide/components/fragments.html

Recommended Posts

Fragment basics
Rails basics
Ruby basics
JPA Basics 1
Docker basics
ViewPager basics
Java basics
Java basics
RSpec Basics
JavaScript basics
JPA Basics 2
Hash basics
Java basics
Ruby basics
RecyclerView Basics
Rails CSV basics
Rails Routing Basics
Rails database basics
Rails Logger Basics
java programming basics
Basics of Ruby
Java JAR basics
Object-oriented (Java) basics
vim (gitbush) basics
Regular expression basics
Java concurrency basics
Rspec Basics [Rails]
Stream API basics