Step 3: Mastering Android Basics - Activities, Layouts, and Views

How Activities, Layouts, and Views work together to build user interfaces.

Welcome to Step 3 of your Android development journey! Now that your development environment is set up, it’s time to understand the foundational concepts of Android app development: Activities, Layouts, and Views. These elements form the core of every Android application. 

Understanding Android Basics - Android Academics



By the end of this guide, you’ll have a solid understanding of these components and be ready to start building your first interactive user interface.


What Are Activities?

An Activity is a single, focused screen in an app. Think of it as the "entry point" for user interaction. Every Android app starts with at least one Activity, often called the MainActivity.

Activity Lifecycle



Key Features of Activities:

  • They act as the controller for the user interface.
  • Each Activity is represented by a Java or Kotlin class.
  • Activities are declared in the AndroidManifest.xml file.

Example: MainActivity in Kotlin

Here’s a basic MainActivity.kt:

package com.example.myfirstapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main) // Links to the layout file
    }
}

In this example, the onCreate method from the Activity Lifecycle initializes the Activity and sets its content view to a layout file (activity_main.xml).

Exercise:

  • Create a second Activity called SecondActivity. Use the New > Activity > Empty Activity option in Android Studio.
  • Add a button in MainActivity that navigates to SecondActivity when clicked

What Are Layouts?

A Layout defines the visual structure of your app's user interface. It organizes Views (buttons, text fields, images) on the screen.

Photo by Hal Gatewood on Unsplash


Why Is UI Design Important?

A well-designed UI is more than just making your app look good—it’s about creating an intuitive and enjoyable experience for users. When your app feels easy to navigate and visually cohesive, users are more likely to engage with it and keep coming back.

Key Components of a Beautiful UI

Before we dive into coding, let’s review some core UI components that help enhance the user experience:
  1. Layouts: The backbone of any UI, layouts define how your app’s elements are arranged on the screen. The most commonly used layouts in Android are:
    • LinearLayout: Arranges items either vertically or horizontally.
    • ConstraintLayout: Provides flexible positioning with constraints.
    • RelativeLayout: Allows positioning relative to other views.
  2. Views: Views are the building blocks of your UI. Some examples are:
    • TextViews for displaying text.
    • ImageViews for displaying images.
    • Buttons for user interaction.
  3. Themes and Styles: Themes control the overall look and feel of your app. They define attributes like colors, fonts, and button styles. Custom styles help give your app a unique identity.


1. Create a New Layout File

Start by creating a new XML layout file. For instance, let's build a simple login screen. Inside your res/layout folder, create activity_login.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/loginTitle"
        android:text="Welcome Back"
        android:textSize="24sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/emailEditText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/emailEditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Email"
        android:inputType="textEmailAddress"
        app:layout_constraintTop_toBottomOf="@+id/loginTitle"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:padding="16dp"
        android:background="@drawable/edit_text_background" />

    <EditText
        android:id="@+id/passwordEditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword"
        app:layout_constraintTop_toBottomOf="@+id/emailEditText"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:padding="16dp"
        android:background="@drawable/edit_text_background" />

    <Button
        android:id="@+id/loginButton"
        android:text="Login"
        android:textColor="#FFFFFF"
        android:background="@color/colorPrimary"
        app:layout_constraintTop_toBottomOf="@+id/passwordEditText"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</androidx.constraintlayout.widget.ConstraintLayout>

In this layout, we have a title, two EditText fields for email and password, and a Button to submit the login form. The ConstraintLayout allows for flexible and efficient UI positioning.

Android Academics-Layout Preview




2. Adding Styling

Now let’s add some basic styles for consistency. Open the res/values/styles.xml file and define a custom theme:

<resources>
    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorSecondary">@color/colorSecondary</item>
        <item name="android:textColorPrimary">@android:color/black</item>
    </style>
</resources>

3. Binding UI Elements in Kotlin

Next, let’s bind our UI elements to the Kotlin code. Open your MainActivity.kt and initialize the views:

package com.example.myapp

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        val emailEditText = findViewById<EditText>(R.id.emailEditText)
        val passwordEditText = findViewById<EditText>(R.id.passwordEditText)
        val loginButton = findViewById<Button>(R.id.loginButton)

        loginButton.setOnClickListener {
            val email = emailEditText.text.toString()
            val password = passwordEditText.text.toString()

            // Handle login logic here
        }
    }
}


In this code, we retrieve the references to the EditText and Button views and set up a click listener for the login button.

4. Enhancing UI with Animations and Transitions

To take your UI to the next level, consider adding animations or transitions. For example, you could add a fade-in animation for the login screen:

<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromAlpha="0.0"
    android:toAlpha="1.0" />

You can then apply this animation to any view to create smooth transitions, enhancing the user experience.


    What Are Views?

    A View is the building block of an app’s UI. It represents a single UI element, such as a button, text field, or image.

    Common Views:

    • TextView: Displays text.
    • EditText: Allows user input.
    • Button: Detects clicks.
    • ImageView: Displays images.

    Example: Adding an EditText and Button in activity_main.xml

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name" />
    
    <Button
        android:id="@+id/submitButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />

    Handling Button Clicks in Kotlin:

    val button: Button = findViewById(R.id.submitButton)
    
    button.setOnClickListener {
        val editText: EditText = findViewById(R.id.editText)
        val enteredText = editText.text.toString()
        Toast.makeText(this, "Hello, $enteredText!", Toast.LENGTH_SHORT).show()
    }

    When the button is clicked, a Toast message displays the entered name.

    Exercise:

    1. Add an ImageView below the EditText. Display a placeholder image from the resources folder.
    2. Create a custom style for the button (e.g., change its color and shape).

    Real-World Use Case: Login Screen

    Combining Activities, Layouts, and Views, let’s create a simple login screen:

    Layout (activity_login.xml):

    <ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <EditText
            android:id="@+id/username"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="Username"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />
    
        <EditText
            android:id="@+id/password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:inputType="textPassword"
            app:layout_constraintTop_toBottomOf="@id/username"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />
    
        <Button
            android:id="@+id/loginButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login"
            app:layout_constraintTop_toBottomOf="@id/password"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />
    
    </ConstraintLayout>

    Kotlin Code (LoginActivity.kt):

    val loginButton: Button = findViewById(R.id.loginButton)
    
    loginButton.setOnClickListener {
        val username: EditText = findViewById(R.id.username)
        val password: EditText = findViewById(R.id.password)
    
        if (username.text.toString().isNotEmpty() && password.text.toString().isNotEmpty()) {
            Toast.makeText(this, "Login Successful", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show()
        }
    }

    Summary

    Understanding Activities, Layouts, and Views is essential for building Android apps. Here’s what you’ve learned:
    1. Activities: Manage user interactions and app lifecycle.
    2. Layouts: Define the visual structure of your app.
    3. Views: Build the UI with interactive elements.

    What’s Next?

    In the next step, we’ll dive deeper into designing beautiful user interfaces. You’ll learn about styles, themes, and advanced layout techniques to create stunning apps.
    • Step 1: Master the Basics of Kotlin Programming for Android Development
    • Step 2: Setting Up Your Development Environment
    • Step 3: Understanding Android Basics — Activities, Layouts, and Views
    • Next -> Step 4: Working with Intents in Android
    • Step 5: Fragments — Dynamic and Modular UI Design
    • Step 6: RecyclerView and Adapters — Displaying Lists of Data
    • Step 7: ViewModel and LiveData — Building Reactive Apps
    • Step 8: Room Database — Local Data Storage
    • Step 9: Networking with Retrofit — Fetching and Sending Data
    • Step 10: Material Design — Enhancing User Experience
    • Step 11: Firebase Integration — Real-time Data and Authentication
    • Step 12: Testing and Debugging — Ensuring App Stability
    • Step 13: Publishing Your App — Taking It Live.

    Stay Tuned! Don’t forget to subscribe and follow for the next steps in this series. Got questions? Drop them in the comments below—I’m here to help!

    Let’s get coding and bring your app ideas to life!

    Pragnesh Ghoda

    A forward-thinking developer offering more than 8 years of experience building, integrating, and supporting android applications for mobile and tablet devices on the Android platform. Talks about #kotlin and #android

    Post a Comment

    Please let us know about any concerns or query.

    Previous Post Next Post

    Contact Form