---
title: Android Basics - Activities & Fragments
description: First article of the Android development collection. In this one we will see what is an activity and fragment and lifecycle of an application
image: https://blog.avenuecode.com/hubfs/Images/Blog/Android%20Basics%202.jpg
---

[AvenueCode.com](https://avenuecode.com) [News](https://avenuecode.com/news) [Contact](https://avenuecode.com/contact)

[![Avenue Code Snippets Logo](https://blog.avenuecode.com/hubfs/Avenue%20Code%20New%20Logos%20-%202023/AC-Snippets---Black.png)](https://blog.avenuecode.com/?hsLang=en-us) *menu*

- Technology
  
  [Cloud](https://blog.avenuecode.com/blog/topic/cloud?hsLang=en-us) [Delivery Infrastructure](https://blog.avenuecode.com/blog/topic/delivery-infrastructure?hsLang=en-us) [Web Experience](https://blog.avenuecode.com/blog/topic/web-experience?hsLang=en-us) [Agile Mindset](https://blog.avenuecode.com/blog/topic/agile-mindset?hsLang=en-us) [Quality First](https://blog.avenuecode.com/blog/topic/quality-first?hsLang=en-us)
  
  [Design](https://blog.avenuecode.com/blog/topic/design?hsLang=en-us) [Solution Architecture](https://blog.avenuecode.com/blog/topic/solution-architecture?hsLang=en-us) [Data & ML](https://blog.avenuecode.com/blog/topic/data-and-machine-learning?hsLang=en-us) [Mobile Experience](https://blog.avenuecode.com/blog/topic/mobile-experience?hsLang=en-us)
- [Whitepapers](https://blog.avenuecode.com/blog/topic/whitepapers?hsLang=en-us)
- [Spotlight](https://blog.avenuecode.com/blog/topic/spotlight?hsLang=en-us)
- [Extraordinary Women in Tech](https://blog.avenuecode.com/blog/topic/extraordinary-women-in-tech?hsLang=en-us)
- [Avenue Code Culture](https://blog.avenuecode.com/blog/topic/avenue-code-culture?hsLang=en-us)

- [Cloud](https://blog.avenuecode.com/blog/topic/cloud?hsLang=en-us)
- [Design](https://blog.avenuecode.com/blog/topic/design?hsLang=en-us)
- [Delivery Infrastructure](https://blog.avenuecode.com/blog/topic/delivery-infrastructure?hsLang=en-us)
- [Solution Architecture](https://blog.avenuecode.com/blog/topic/solution-architecture?hsLang=en-us)
- [Web Experience](https://blog.avenuecode.com/blog/topic/web-experience?hsLang=en-us)
- [Data & ML](https://blog.avenuecode.com/blog/topic/data-and-machine-learning?hsLang=en-us)
- [Agile Mindset](https://blog.avenuecode.com/blog/topic/agile-mindset?hsLang=en-us)
- [Mobile Experience](https://blog.avenuecode.com/blog/topic/mobile-experience?hsLang=en-us)
- [Quality First](https://blog.avenuecode.com/blog/topic/quality-first?hsLang=en-us)
- [Whitepapers](https://blog.avenuecode.com/blog/topic/whitepapers?hsLang=en-us)
- [Spotlight](https://blog.avenuecode.com/blog/topic/spotlight?hsLang=en-us)
- [Extraordinary Women in Tech](https://blog.avenuecode.com/blog/topic/extraordinary-women-in-tech?hsLang=en-us)
- [Avenue Code Culture](https://blog.avenuecode.com/blog/topic/avenue-code-culture?hsLang=en-us)

# [Android Basics - Activities & Fragments](https://blog.avenuecode.com/android-basics-activities-fragments)

- [Tweet](https://twitter.com/share)

*perm\_identity* [André Servidoni](https://blog.avenuecode.com/android-basics-activities-fragments/author/andr%C3%A9-servidoni?hsLang=en-us)

*schedule* 2/22/17 5:46 PM

In this collection of articles about Android, I will guide you through the basic topics that you'll need to get started in this mobile world - even if you're completely new to the Android operating system. 

## Android Basics

Let's start with a little history: What is Android?

According to [Wikipedia](https://simple.wikipedia.org/wiki/Android_(operating_system)),

> "Android is a mobile operating system developed by Google, based on the Linux kernel and designed primarily for touchscreen mobile devices such as smartphones and tablets. Android's user interface is mainly based on direct manipulation, using touch gestures that loosely correspond to real-world actions, such as swiping, tapping and pinching, to manipulate on-screen objects, along with a virtual keyboard for text input."

As the most of you know, the Android system runs its features using applications.

So, let's take a deeper look.

## Styles & Fragments

In this first article we will talk about activities, fragments, show example codes, and look at the lifecycle of the Android application.

1. **Activity** is the part where the user will interacts with your application. In other words, it is responsible for creating a window to hold your UI components. (UI components and how to build a layout will be discussed in another article).
2. **Fragment** represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and to which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities). And it must always be embedded in an activity. The fragment's lifecycle is directly affected by the host activity's lifecycle - in other words, a fragment cannot be instantiated alone!

## Lifecycle

When an application is opened and shows its first activity, it follow a specific lifecycle. Within this, you can handle when the activity is destroyed, paused, resumed, or created.

The fragment lifecycle is embedded within the activity lifecycle but has some details and extra steps in it. The following image compares both lifecycles: on the left, the activity, and on the right, the fragment:

![The activity and fragment lifecycles (1).png](https://blog.avenuecode.com/hs-fs/hubfs/The%20activity%20and%20fragment%20lifecycles%20(1).png?width=640&name=The%20activity%20and%20fragment%20lifecycles%20(1).png)

[*Source*](https://developer.android.com/guide/components/activities/activity-lifecycle.html#alc)

In the image we can see a lot of callbacks. Some we must implement, and others no. But what is the correct execution order, and which ones do we need to implement?

The only mandatory callback that we should override is **onCreate** for the activity and **onCreateView** for fragment, because we define the layout and do the mapping of the UI components inside of them.

When an activity is coming to the foreground and becoming visible to the user, it goes through the **onCreate** method that creates the activity layout, from the XML. After that it will go through the **onStart** and soon after the "onResume", in which the activity is already visible on the screen.

Now when we enter the background (we pressed home or another activity entered in front of it) it goes to the **onStop** method and when it comes back to the foreground it executes the **onRestart** methods and then the **onStart** and **onResume** normally, since it was only in the background and does not need to be re-created.

And finally when the activity is destroyed, for any reason (for example, pressing the back button) it follows the following flow: **onStop** and **onDestroy** in which all the resources of this activity are released and it exits the system activity stack. In this case, if we call this activity again, as it was destroyed, then it will start its flow from the **onCreate **because it needs to be re-created and added again in the stack.

So let's put together all this information:

1. **onCreate(activities) / onCreateView(fragments):** The only required method (that is, it needs to be overwritten by the class that extends Activity) defines what the layout of that activity is (with the "setContentView" method) and where the XML components are mapped to the code.
2. **onStart:** This method is always executed right after the onCreate and whenever the activity returns from background to foreground through onRestart.
3. **onResume:** It always runs before the application appears to the user. At that moment this activity is already at the top of the activity stack and is visible to the user.
4. **onPause:** Called when the system is about to start resuming another activity. This method is generally used to confirm unsaved data changes, stop animations among other things that may be consuming CPU, and so on.
5. **onRestart:** Called when an activity that was stopped in the background is returning to the foreground because the activity that was visible above it is being destroyed or called. It always runs when an activity is in the STOP state.
6. **onStop:** Called when the activity is no longer visible to the user. This can happen because it is being destroyed or is going to background so that another activity takes its place at the top of the stack and is visible to the user.
7. **onDestroy:** Called before destroying the activity. This is the last call that activity will take when it is leaving the activity stack - that is, it is being destroyed - it is called because the activity is terminating (someone called finish ()), or because the system is temporarily destroying this activity instance to save space.

Now that we know about the theory, have a look at the code! Examples can be found by following the github link at the end of this article.

## Layout

First let's take a look at the layout file. An Android layout is where the visual structure of your app or widget is set. In it are placed the components that will appear on the screen and perform the tools to interact with the user.

There are 2 ways to instantiate Android graphics components:

1. First - and highly recommended - create the elements in an XML file.
2. Second, instantiate the graphical elements at runtime, by the code of your application.

Declaring the whole layout part of your app in an XML file, we were able to separate the graphical interface from the source code, leaving the structure of the project more organized and easier to understand.

Following we have an simple layout of a login screen in the XML:

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

`<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" `

`                android:layout_width="match_parent"`

`                android:layout_height="match_parent"`

`                android:orientation="vertical">`

 

`    <TextView`

`        android:layout_width="match_parent"`

`        android:layout_height="wrap_content"`

`        android:layout_marginBottom="50dip"`

`        android:layout_marginTop="40dip"`

`        android:gravity="center"`

`        android:textSize="20sp"`

`        android:textStyle="bold"`

`        android:text="@string/app_name"/>`

 

`    <TextView android:layout_width="match_parent"`

`        android:layout_height="wrap_content"`

`        android:layout_marginTop="10dip"`

`        android:gravity="center"`

`        android:textSize="16sp"`

`        android:text="@string/username"/>`

 

`    <EditText android:id="@+id/main_user_input"`

`              android:layout_width="match_parent"`

`              android:layout_height="wrap_content"`

`              android:layout_marginStart="10dip"`

`              android:layout_marginEnd="10dip"`

`              android:inputType="text"`

`              android:gravity="center"/>`

 

`    <TextView android:layout_width="match_parent"`

`              android:layout_height="wrap_content"`

`              android:layout_marginTop="30dip"`

`              android:gravity="center"`

`              android:textSize="16sp"`

`              android:text="@string/password"/>`

 

`    <EditText android:id="@+id/main_password_input"`

`              android:layout_width="match_parent"`

`              android:layout_height="wrap_content"`

`              android:layout_marginStart="10dip"`

`              android:layout_marginEnd="10dip"`

`              android:inputType="textPassword"`

`              android:gravity="center"/>`

 

`    <Button`

`        android:id="@+id/main_button_login"`

`        android:layout_width="match_parent"`

`        android:layout_height="40dip"`

`        android:layout_margin="30dip"`

`        android:text="@string/login"/>`

 

`</LinearLayout> `

## Binding the Layout

Now that we already did the XML for our screen, we need to tell the activity which layout to use and "bind" the components of the XML with the code, so we can get info and/or handle user interactions.

For this we will use the method **setContentView** inside the **onCreate** *(in activity)* or **onCreateView** *(in fragment)* to tell the code the layout of that screen.

In the following example we set the layout and after that we "bind" the element from the layout using the **findViewById** method that will search for a *view* in the XML with the respective **id**. We do a cast, (EditText), because the find view returns a parent view object.

`public class MainActivity extends Activity {`

 

`    private EditText mUserInput = null;`

`    private EditText mPassInput = null;`

 

`    @Override`

`    protected void onCreate(Bundle savedInstanceState) {`

`        super.onCreate(savedInstanceState);`

 

`        setContentView(R.layout.activity_main);`

 

`        mUserInput = (EditText) findViewById(R.id.main_user_input);`

`        mPassInput = (EditText) findViewById(R.id.main_password_input);`

`        Button loginButton = (Button) findViewById(R.id.main_button_login);`

 

`        loginButton.setOnClickListener(new View.OnClickListener() {`

 

`            @Override`

`            public void onClick(View view) {`

`                // do something when click`

`            }`

`        });`

`    }`

`}`

To do this in the fragment it's a little different but the concept is the same.  Let's take a look at the example.

The **onCreateView** need to return the inflated view to its parent, so we use the layout inflater parameter to reference the view for the specific layout (in this case R.layout.activity\_main). 

 After that we "bind" the components from the inflated view object and at the end we return it.

`public class ExampleFragment extends Fragment { `

`    @Override`

`    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {`

`        // Inflate the layout for this fragment`

`        View inflatedView = inflater.inflate(R.layout.activity_main, container, false);`

 

`        mUserInput = (EditText) inflatedView.findViewById(R.id.main_user_input);`

`        mPassInput = (EditText) inflatedView.findViewById(R.id.main_password_input);`

 

`        return inflatedView;`

`    }`

`}`

## To Conclude

Today we covered the basics for creating a simple screen activity and binding the layout components with code in order to manipulate it.

In future articles we'll discuss other topics such as persistence, network and application flow.

**Thanks for reading and feel free to reach out to me with any questions about it!**

**All the code is available at my github, feel free to use it: **[**https://github.com/DeKoServidoni/android\_study**](https://github.com/DeKoServidoni/android_study)

 

---

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Blog/facebook.png)](https://www.facebook.com/deko.servidoni) [![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Blog/twitter.png)](https://twitter.com/DeKoServidoni) [![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Blog/linkedin.png)](https://br.linkedin.com/in/andreservidoni)

### Author

# André Servidoni

 André Servidoni is an Android Engineer at Avenue Code. He is a new technologies enthusiast, and he is addicted to PS4.

---

### Related Posts

### Building Accessible Web Applications

[READ MORE](https://blog.avenuecode.com/building-accessible-web-applications?hsLang=en-us)

### Create a Tunnel from Anypoint Platform to GCP Using an HA VPN

[READ MORE](https://blog.avenuecode.com/create-a-tunnel-from-anypoint-platform-to-gcp-using-ha-vpn?hsLang=en-us)

### Create a Classic Tunnel from GCP to Anypoint Platform

[READ MORE](https://blog.avenuecode.com/create-a-classic-tunnel-from-gcp-to-anypoint-platform?hsLang=en-us)

### How to Make an Android Splash Screen

[READ MORE](https://blog.avenuecode.com/how-to-make-an-android-splash-screen?hsLang=en-us)

### Leave a Comment!

### Avenue Code Social

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Blog/facebook.png?t=1486470796564)](https://www.facebook.com/avenuecode)

[![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Blog/twitter.png?t=1486470796842)](https://twitter.com/AvenueCode)

[![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Blog/linkedin.png?t=1486470796556)](https://www.linkedin.com/company/avenue-code)

### Newsletter

Want to stay on top of all tips and news from Avenue Code?

### Popular Snippets

![ac-logo-inverted.svg](https://blog.avenuecode.com/hubfs/Images/Logos/ac-logo-inverted.svg "ac-logo-inverted.svg")

### About Us

- [Who We Are](https://www.avenuecode.com/who-we-are)
- [What We Do](https://www.avenuecode.com/what-we-do)
- [Portfolio](https://www.avenuecode.com/portfolio)
- [Partners](https://www.avenuecode.com/partners)
- [News](https://www.avenuecode.com/news)
- [Events](https://www.avenuecode.com/events)
- [Blog](https://blog.avenuecode.com/)
- [Contact](https://www.avenuecode.com/contact)

### Our Offices

San Francisco

[+1 415 766 4178](tel:+553125161448) [ac.inquiries@avenuecode.com](mailto:brazil.info@avenuecode.com)

Belo Horizonte

[+55 31 2516 1448](tel:+553125161448) [brazil.info@avenuecode.com](mailto:brazil.info@avenuecode.com)

São Paulo

[+55 11 3205 3232](tel:+553125161448) [brazil.info@avenuecode.com](mailto:brazil.info@avenuecode.com)

### We're Hiring!

- [Belo Horizonte](https://www.avenuecode.com/who-we-are)
- [New York](https://www.avenuecode.com/what-we-do)
- [San Francisco](https://www.avenuecode.com/portfolio)
- [São Paulo](https://www.avenuecode.com/partners)

---

©2015 - 2017 Avenue Code

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Icons/facebook-2.png)](https://www.facebook.com/avenuecode) [![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Icons/twitter-2.png)](https://twitter.com/AvenueCode) [![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Icons/linkedin-2.png)](https://www.linkedin.com/company/avenue-code) [![Glassdoor Icon](https://blog.avenuecode.com/hubfs/Images/Icons/glassdoor-icon-1.png)](https://www.glassdoor.com/Overview/Working-at-Avenue-Code-EI_IE456173.11,22.htm) [![YouTube Icon](https://blog.avenuecode.com/hubfs/Images/Icons/youtube-2.png)](https://www.youtube.com/user/AvenueCodePlay)

Please enable JavaScript to view the [comments powered by Disqus.](http://disqus.com/?ref_noscript)

© 2026 Avenue Code

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "André Servidoni",
    "url" : "https://blog.avenuecode.com/author/andré-servidoni"
  },
  "dateModified" : "2022-10-12T19:53:24.639Z",
  "datePublished" : "2017-02-22T20:46:22.000Z",
  "headline" : "Android Basics - Activities & Fragments",
  "image" : [ "https://blog.avenuecode.com/hubfs/Images/Blog/Android%20Basics%202.jpg" ],
  "mainEntityOfPage" : {
    "@id" : "https://blog.avenuecode.com/android-basics-activities-fragments",
    "@type" : "WebPage"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://blog.avenuecode.com/hubfs/Avenue%20Code%20New%20Logos%20-%202023/Avenue%20Code-primary%20versions_LOGO%20HORIZONTAL%20group%201-7.png"
    },
    "name" : "Avenue Code"
  }
}
```