Saturday, October 26, 2019

Android Up Button Tutorial — Back Navigation in Android Toolbar

No comments email this post Edit Post

Navigation is one of the most important parts of Android application development.

Android provides:

  • Back button navigation
  • Up button navigation
  • Navigation Component
  • Toolbar navigation

In this tutorial, we will learn how to implement:

  • Toolbar Up Button
  • Parent Activity navigation
  • AndroidManifest parent activities
  • Modern AndroidX navigation
  • Multi-activity back navigation

What Is Up Button in Android?

The Up Button is the back arrow shown inside the Toolbar or ActionBar.

It allows users to navigate:

  • Back to parent Activity
  • Up in application hierarchy
  • Between related screens

Difference Between Back Button and Up Button

Back Button Up Button
System navigation App hierarchy navigation
Returns previous screen Returns parent screen
Managed by Android system Managed by app developer

What We Will Build

In this example:

  • MainActivity opens Activity2
  • Activity2 opens Activity3
  • Toolbar Up Button navigates backward
  • Parent hierarchy handled automatically

Important Modern Android Note

Older tutorials use:


android.support.*

which is deprecated.

Modern Android applications should use:


androidx.*

Step 1 — Configure Parent Activities in AndroidManifest.xml

Every child activity should define:


android:parentActivityName

Modern Manifest Example


<application>

    <activity
        android:name=".Activity2"
        android:parentActivityName=
            ".MainActivity"/>

    <activity
        android:name=".Activity3"
        android:parentActivityName=
            ".Activity2"/>

    <activity
        android:name=".MainActivity">

        <intent-filter>

            <action
                android:name=
                "android.intent.action.MAIN"/>

            <category
                android:name=
                "android.intent.category.LAUNCHER"/>

        </intent-filter>

    </activity>

</application>

What Is parentActivityName?

This attribute defines the parent screen hierarchy.

Android uses it for:

  • Toolbar Up navigation
  • Task stack generation
  • Navigation consistency

Step 2 — Create MainActivity Layout

Create:


res/layout/activity_main.xml

Modern ConstraintLayout Version


<?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"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <Button

        android:id="@+id/button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Open Activity 2"

        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Why Use ConstraintLayout?

ConstraintLayout provides:

  • Better rendering performance
  • Responsive layouts
  • Flat hierarchy
  • Flexible positioning

Step 3 — Create MainActivity.java


package com.example.upbutton;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity
        extends AppCompatActivity {

    @Override
    protected void onCreate(
            Bundle savedInstanceState
    ) {

        super.onCreate(
                savedInstanceState
        );

        setContentView(
                R.layout.activity_main
        );

        Button button =
                findViewById(
                        R.id.button
                );

        button.setOnClickListener(
                view -> {

                    Intent intent =
                            new Intent(
                                    this,
                                    Activity2.class
                            );

                    startActivity(intent);
                }
        );
    }
}

Step 4 — Create Activity2.java


package com.example.upbutton;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class Activity2
        extends AppCompatActivity {

    @Override
    protected void onCreate(
            Bundle savedInstanceState
    ) {

        super.onCreate(
                savedInstanceState
        );

        setContentView(
                R.layout.activity_2
        );

        if (
            getSupportActionBar()
            != null
        ) {

            getSupportActionBar()
                    .setTitle(
                            "Activity 2"
                    );

            getSupportActionBar()
                    .setDisplayHomeAsUpEnabled(
                            true
                    );
        }

        Button button2 =
                findViewById(
                        R.id.button2
                );

        button2.setOnClickListener(
                view -> {

                    Intent intent =
                            new Intent(
                                    this,
                                    Activity3.class
                            );

                    startActivity(intent);
                }
        );
    }
}

Understanding setDisplayHomeAsUpEnabled()

This method enables Toolbar Up Button.


Example


getSupportActionBar()
        .setDisplayHomeAsUpEnabled(
                true
        );

Step 5 — Create Activity3.java


package com.example.upbutton;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class Activity3
        extends AppCompatActivity {

    @Override
    protected void onCreate(
            Bundle savedInstanceState
    ) {

        super.onCreate(
                savedInstanceState
        );

        setContentView(
                R.layout.activity_3
        );

        if (
            getSupportActionBar()
            != null
        ) {

            getSupportActionBar()
                    .setTitle(
                            "Activity 3"
                    );

            getSupportActionBar()
                    .setDisplayHomeAsUpEnabled(
                            true
                    );
        }
    }
}

How Up Navigation Works

  1. User opens Activity2
  2. Toolbar arrow appears
  3. User taps Up Button
  4. Android checks parentActivityName
  5. Parent Activity opens

Activity Navigation Hierarchy


MainActivity
    ↓
Activity2
    ↓
Activity3

Modern Toolbar Recommendation

Modern Android apps should use:

  • MaterialToolbar
  • Navigation Component
  • Single Activity Architecture
  • Jetpack Compose Navigation

Modern Material Toolbar Example


<com.google.android.material.appbar.MaterialToolbar

    android:id="@+id/toolbar"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"/>

Navigation Component Alternative

Modern Android applications now commonly use:


Navigation Component

instead of multiple activities.


Benefits of Navigation Component

  • Automatic back stack handling
  • Safe navigation
  • Fragment navigation
  • Deep links
  • Animated transitions

Jetpack Compose Alternative

Jetpack Compose uses:


NavHost

and:


TopAppBar

for modern navigation systems.


Compose Navigation Example


NavHost(
    navController = navController,
    startDestination = "home"
)

Common Beginner Mistakes

1. Forgetting parentActivityName

Up navigation requires Manifest hierarchy configuration.


2. NullPointerException on ActionBar

Always check:


getSupportActionBar() != null

3. Using Deprecated Support Libraries

Always migrate to AndroidX.


Best Practices

  • Use MaterialToolbar
  • Use Navigation Component
  • Keep navigation hierarchy clean
  • Use AndroidX libraries
  • Prefer single activity architecture

FAQ

What is Up Button in Android?

Up Button is Toolbar back navigation for parent Activity hierarchy.


How do I enable Up Button?

Use:


setDisplayHomeAsUpEnabled(true)

What is the modern navigation solution?

Navigation Component and Jetpack Compose Navigation are modern solutions.


Conclusion

The Android Up Button provides clean hierarchical navigation between screens and improves application usability.

It is an essential part of Android navigation architecture and Toolbar design.

Modern Android applications should combine AndroidX, Material Design, Navigation Component, and scalable architecture for production-grade navigation systems.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Open New Activity on Button Click in Android — Intent Tutorial

No comments email this post Edit Post

Activities are one of the most important building blocks in Android applications.

Every Android screen is usually represented by an:


Activity

In this tutorial, we will learn:

  • What an Activity is
  • How to open a new Activity
  • How Android Intent works
  • How to navigate between screens
  • How to register Activities in Manifest
  • Modern AndroidX implementation

What Is an Activity in Android?

An Activity represents a single screen with a user interface.

Examples:

  • Login screen
  • Home screen
  • Profile screen
  • Settings screen
  • Checkout screen

What Is an Intent?

Intent is a messaging object used for:

  • Opening activities
  • Starting services
  • Sending broadcasts
  • Sharing data between components

Types of Intents

Explicit Intent Implicit Intent
Targets specific Activity Targets external action
Inside app navigation Open browser, camera etc.

What We Will Build

In this example:

  • User clicks button
  • Intent created
  • Second Activity opens
  • User navigates to another screen

Important Modern Android Note

Older tutorials use:


android.support.*

which is deprecated.

Modern Android applications should use:


androidx.*

Step 1 — Create activity_main.xml

Create:


res/layout/activity_main.xml

Modern ConstraintLayout Version


<?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"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Activity 1"

        android:textSize="24sp"

        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintEnd_toEndOf="parent"/>

    <Button

        android:id="@+id/button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Open Activity 2"

        android:layout_marginTop="16dp"

        app:layout_constraintTop_toBottomOf="@id/textView"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Why Use ConstraintLayout?

ConstraintLayout provides:

  • Better rendering performance
  • Responsive layouts
  • Flat hierarchy
  • Flexible positioning

Step 2 — Create MainActivity.java


package com.example.openactivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity
        extends AppCompatActivity {

    private Button button;

    @Override
    protected void onCreate(
            Bundle savedInstanceState
    ) {

        super.onCreate(
                savedInstanceState
        );

        setContentView(
                R.layout.activity_main
        );

        button =
                findViewById(
                        R.id.button
                );

        button.setOnClickListener(
                view -> openActivity2()
        );
    }

    private void openActivity2() {

        Intent intent =
                new Intent(
                        MainActivity.this,
                        Activity2.class
                );

        startActivity(intent);
    }
}

Understanding Intent


Intent intent =
        new Intent(
                MainActivity.this,
                Activity2.class
        );

This creates an explicit intent targeting:


Activity2

What Does startActivity() Do?

The:


startActivity()

method launches the target activity.


Navigation Flow

  1. User clicks button
  2. Intent created
  3. Android resolves Activity
  4. Activity2 opens

Step 3 — Create activity_2.xml

Create:


res/layout/activity_2.xml

Modern activity_2.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"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Activity 2"

        android:textSize="24sp"

        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Step 4 — Create Activity2.java


package com.example.openactivity;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class Activity2
        extends AppCompatActivity {

    @Override
    protected void onCreate(
            Bundle savedInstanceState
    ) {

        super.onCreate(
                savedInstanceState
        );

        setContentView(
                R.layout.activity_2
        );
    }
}

Step 5 — Register Activity in AndroidManifest.xml

Every Activity must be declared inside:


AndroidManifest.xml

Manifest Example


<application>

    <activity
        android:name=".Activity2"/>

    <activity
        android:name=".MainActivity">

        <intent-filter>

            <action
                android:name=
                "android.intent.action.MAIN"/>

            <category
                android:name=
                "android.intent.category.LAUNCHER"/>

        </intent-filter>

    </activity>

</application>

Why Manifest Registration Is Important

If Activity is not registered:

  • Application crashes
  • Android cannot resolve Intent
  • Navigation fails

Explicit Intent vs Implicit Intent

Explicit Intent Example


Intent intent =
        new Intent(
                this,
                Activity2.class
        );

Implicit Intent Example


Intent intent =
        new Intent(
                Intent.ACTION_VIEW
        );

Passing Data Between Activities

Intent also supports data transfer.


Example — Pass Data


intent.putExtra(
        "username",
        "Salil"
);

Retrieve Data in Activity2


String username =
        getIntent().getStringExtra(
                "username"
        );

Modern Android Recommendations

Modern Android applications commonly use:

  • Navigation Component
  • Safe Args
  • Single Activity Architecture
  • Fragments
  • Jetpack Compose Navigation

What Is Navigation Component?

Navigation Component simplifies:

  • Screen navigation
  • Back stack handling
  • Fragment transactions
  • Safe data passing

Jetpack Compose Alternative

Modern Android apps using Compose now use:


NavHost

and:


Composable navigation

Common Beginner Mistakes

1. Forgetting Manifest Registration

Every Activity must be registered.


2. Using Deprecated Support Libraries

Always migrate to AndroidX.


3. NullPointerException

Always initialize Views correctly using:


findViewById()

Best Practices

  • Use AndroidX
  • Use Navigation Component
  • Keep Activities lightweight
  • Use MVVM architecture
  • Pass only necessary data

FAQ

What is an Activity?

An Activity represents a single Android screen.


What is an Intent?

Intent is used for communication between Android components.


Why register Activity in Manifest?

Android needs Manifest registration to launch activities.


Conclusion

Opening a new Activity using Intent is one of the most fundamental concepts in Android development.

It enables screen navigation, modular UI architecture, and communication between application components.

Modern Android applications should combine AndroidX, Navigation Component, MVVM architecture, and scalable UI design for production-grade development.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Thursday, October 24, 2019

Android RecyclerView & CardView Tutorial — Modern List UI in Android

No comments email this post Edit Post

RecyclerView is one of the most important UI components in Android development.

It is used to efficiently display:

  • Large lists
  • Dynamic data
  • Grid layouts
  • Chats
  • Feeds
  • E-commerce product lists

RecyclerView provides much better performance and flexibility compared to the old ListView component.


What Is RecyclerView?

RecyclerView is a flexible and advanced version of ListView introduced by Android Jetpack libraries.

RecyclerView:

  • Reuses item views efficiently
  • Improves scrolling performance
  • Supports animations
  • Supports multiple layouts
  • Works with adapters

What Is CardView?

CardView is a UI component that displays content inside material design cards.

CardView provides:

  • Rounded corners
  • Elevation shadows
  • Material design feel
  • Beautiful list presentation

RecyclerView vs ListView

ListView RecyclerView
Older component Modern component
Limited optimization Highly optimized
Less flexible Highly customizable
No ViewHolder by default Uses ViewHolder pattern

Modern AndroidX Dependencies

Inside:


build.gradle

Add:


implementation
'androidx.recyclerview:recyclerview:1.3.2'

implementation
'androidx.cardview:cardview:1.0.0'

implementation
'com.github.bumptech.glide:glide:4.16.0'

Important Modernization

Older tutorials use:


android.support.v7.widget.RecyclerView

which is deprecated.

Modern Android applications should use:


androidx.recyclerview.widget.RecyclerView

Modern 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"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView

        android:id="@+id/recyclerView"

        android:layout_width="0dp"

        android:layout_height="0dp"

        android:padding="8dp"

        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Create Item Layout

Create:


item_example.xml

Modern CardView Item Layout


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

<androidx.cardview.widget.CardView

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

    xmlns:app=
    "http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_margin="8dp"

    app:cardCornerRadius="12dp"

    app:cardElevation="6dp">

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal"

        android:padding="12dp">

        <ImageView

            android:id="@+id/imageView"

            android:layout_width="60dp"

            android:layout_height="60dp"

            android:scaleType="centerCrop"/>

        <LinearLayout

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:orientation="vertical"

            android:layout_marginStart="12dp">

            <TextView

                android:id="@+id/textView"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="Android"

                android:textStyle="bold"

                android:textSize="20sp"/>

            <TextView

                android:id="@+id/textView2"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="RecyclerView Example"

                android:textSize="15sp"/>

        </LinearLayout>

    </LinearLayout>

</androidx.cardview.widget.CardView>

Create Model Class

Create:


ExampleItem.java

ExampleItem.java


public class ExampleItem {

    private int imageResource;

    private String text1;

    private String text2;

    public ExampleItem(
            int imageResource,
            String text1,
            String text2
    ) {

        this.imageResource = imageResource;

        this.text1 = text1;

        this.text2 = text2;
    }

    public int getImageResource() {
        return imageResource;
    }

    public String getText1() {
        return text1;
    }

    public String getText2() {
        return text2;
    }
}

Create RecyclerView Adapter

RecyclerView requires:

  • Adapter
  • ViewHolder
  • LayoutManager

Modern RecyclerView Adapter


public class RecyclerViewAdapter extends
RecyclerView.Adapter<
RecyclerViewAdapter.ViewHolder> {

    private ArrayList<ExampleItem>
            exampleList;

    private Context context;

    public RecyclerViewAdapter(
            ArrayList<ExampleItem>
                    exampleList,
            Context context
    ) {

        this.exampleList = exampleList;

        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(
            @NonNull ViewGroup parent,
            int viewType
    ) {

        View view =
                LayoutInflater.from(
                        parent.getContext()
                ).inflate(
                        R.layout.item_example,
                        parent,
                        false
                );

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(
            @NonNull ViewHolder holder,
            int position
    ) {

        ExampleItem currentItem =
                exampleList.get(position);

        holder.textView.setText(
                currentItem.getText1()
        );

        holder.textView2.setText(
                currentItem.getText2()
        );

        Glide.with(context)
                .load(
                        currentItem
                                .getImageResource()
                )
                .into(holder.imageView);
    }

    @Override
    public int getItemCount() {
        return exampleList.size();
    }

    public static class ViewHolder
            extends RecyclerView.ViewHolder {

        ImageView imageView;

        TextView textView;

        TextView textView2;

        public ViewHolder(
                @NonNull View itemView
        ) {

            super(itemView);

            imageView =
                    itemView.findViewById(
                            R.id.imageView
                    );

            textView =
                    itemView.findViewById(
                            R.id.textView
                    );

            textView2 =
                    itemView.findViewById(
                            R.id.textView2
                    );
        }
    }
}

Setup RecyclerView in MainActivity


RecyclerView recyclerView;

RecyclerViewAdapter adapter;

ArrayList<ExampleItem>
        exampleList;

MainActivity.java


public class MainActivity
        extends AppCompatActivity {

    RecyclerView recyclerView;

    RecyclerViewAdapter adapter;

    ArrayList<ExampleItem>
            exampleList;

    @Override
    protected void onCreate(
            Bundle savedInstanceState
    ) {

        super.onCreate(
                savedInstanceState
        );

        setContentView(
                R.layout.activity_main
        );

        recyclerView =
                findViewById(
                        R.id.recyclerView
                );

        exampleList =
                new ArrayList<>();

        exampleList.add(
                new ExampleItem(
                        R.drawable.ic_android,
                        "Android",
                        "RecyclerView"
                )
        );

        exampleList.add(
                new ExampleItem(
                        R.drawable.ic_music,
                        "Music",
                        "Top Songs"
                )
        );

        exampleList.add(
                new ExampleItem(
                        R.drawable.ic_work,
                        "Tasks",
                        "Workout"
                )
        );

        adapter =
                new RecyclerViewAdapter(
                        exampleList,
                        this
                );

        recyclerView.setHasFixedSize(
                true
        );

        recyclerView.setLayoutManager(
                new LinearLayoutManager(
                        this
                )
        );

        recyclerView.setAdapter(
                adapter
        );
    }
}

What Is ViewHolder?

ViewHolder improves performance by:

  • Reusing item views
  • Reducing findViewById calls
  • Optimizing scrolling

What Is LayoutManager?

LayoutManager controls item arrangement.


Types of LayoutManagers

  • LinearLayoutManager
  • GridLayoutManager
  • StaggeredGridLayoutManager

LinearLayoutManager

Displays items vertically or horizontally.


GridLayoutManager

Displays items in grid format.


StaggeredGridLayoutManager

Displays Pinterest-style staggered layouts.


Why RecyclerView Is Fast

RecyclerView improves performance using:

  • View recycling
  • ViewHolder pattern
  • Optimized rendering
  • Efficient animations

Modern Android Recommendations

Modern Android applications commonly use:

  • RecyclerView
  • ViewBinding
  • DiffUtil
  • ListAdapter
  • Paging 3
  • Jetpack Compose LazyColumn

RecyclerView + DiffUtil

DiffUtil improves RecyclerView performance by updating only changed items.


What Is ListAdapter?

ListAdapter is a modern RecyclerView adapter with built-in DiffUtil support.


Jetpack Compose Alternative

Modern Android apps can also use:


LazyColumn

inside Jetpack Compose.


Common Beginner Mistakes

1. Forgetting LayoutManager

RecyclerView requires a LayoutManager.


2. Using notifyDataSetChanged Excessively

Use DiffUtil for efficient updates.


3. Loading Large Images Incorrectly

Use Glide or Coil for image optimization.


Best Practices

  • Use ViewBinding
  • Use DiffUtil
  • Use ListAdapter
  • Optimize images
  • Keep layouts lightweight

FAQ

Why use RecyclerView?

RecyclerView provides high-performance scrolling and flexible list UI.


Is ListView deprecated?

ListView still works but RecyclerView is recommended.


What replaces RecyclerView in Compose?

Jetpack Compose uses LazyColumn and LazyRow.


Conclusion

RecyclerView and CardView are essential Android UI components for building scalable, responsive, and modern list interfaces.

Modern Android applications should combine RecyclerView, DiffUtil, ViewBinding, Material Design, and optimized adapters for production-grade performance.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Wednesday, October 23, 2019

How to Use CoordinatorLayout, Bottom Sheets, FloatingActionButton, and Snackbar in Android

No comments email this post Edit Post

Modern Android applications use interactive UI components to create smooth and responsive user experiences.

Some of the most commonly used Material Design components are:

  • CoordinatorLayout
  • Bottom Sheets
  • FloatingActionButton (FAB)
  • Snackbar

In this tutorial, we will learn how these components work together using:

  • CoordinatorLayout behaviors
  • BottomSheetBehavior
  • Snackbar animations
  • FloatingActionButton interactions
  • Material Design components

What We Will Build

In this Android example:

  • Create a Bottom Sheet
  • Show Snackbar messages
  • Use FloatingActionButton
  • Expand Bottom Sheet dynamically
  • Use CoordinatorLayout behaviors
  • Understand layout_insetEdge and layout_dodgeInsetEdges

Important Modern Android Note

The original project uses:


android.support.*

which is deprecated.

Modern Android applications should now use:


androidx.*

and:


com.google.android.material

libraries.


What Is CoordinatorLayout?

CoordinatorLayout is a powerful ViewGroup introduced with Material Design.

It coordinates animations and interactions between child views automatically.

Examples:

  • FAB moving above Snackbar
  • Bottom sheets sliding
  • Collapsing toolbars
  • Scrolling animations

What Are layout_insetEdge and layout_dodgeInsetEdges?

These attributes help views avoid overlapping each other inside CoordinatorLayout.


layout_insetEdge

Defines which edge occupies layout space.

Example:


app:layout_insetEdge="bottom"

layout_dodgeInsetEdges

Moves views away from occupied edges automatically.

Example:


app:layout_dodgeInsetEdges="bottom"

Modern Material Dependency

Inside:


build.gradle

Add:


implementation
'com.google.android.material:material:1.11.0'

Why Material Components?

Material Components provide:

  • Modern UI widgets
  • Material Design styling
  • Better animations
  • Dark mode support
  • Accessibility improvements

Step 1 — Create activity_main.xml

Create:


res/layout/activity_main.xml

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

<androidx.coordinatorlayout.widget.CoordinatorLayout

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

    xmlns:app=
    "http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <com.google.android.material.floatingactionbutton.FloatingActionButton

        android:id="@+id/fab"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_gravity="bottom|end"

        android:layout_margin="16dp"

        android:contentDescription=
        "Show Snackbar"

        app:srcCompat=
        "@android:drawable/ic_input_add"/>

    <Button
        android:id="@+id/button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_gravity="bottom|start"

        android:layout_margin="16dp"

        android:text="Open Bottom Sheet"

        app:layout_dodgeInsetEdges=
        "bottom"/>

    <androidx.core.widget.NestedScrollView

        android:id="@+id/bottom_sheet"

        android:layout_width="match_parent"

        android:layout_height="350dp"

        android:background=
        "@android:color/holo_blue_light"

        app:behavior_hideable="true"

        app:behavior_peekHeight="0dp"

        app:layout_behavior=
        "@string/bottom_sheet_behavior"

        app:layout_insetEdge="bottom">

        <TextView
            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:padding="16dp"

            android:text="@string/dummy_text"

            android:textSize="16sp"/>

    </androidx.core.widget.NestedScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Step 2 — Create MainActivity.java

Create:


package com.example.bottomsheetdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

public class MainActivity
        extends AppCompatActivity {

    private BottomSheetBehavior<View>
            bottomSheetBehavior;

    @Override
    protected void onCreate(
            Bundle savedInstanceState
    ) {

        super.onCreate(savedInstanceState);

        setContentView(
                R.layout.activity_main
        );

        View bottomSheet =
                findViewById(
                        R.id.bottom_sheet
                );

        bottomSheetBehavior =
                BottomSheetBehavior
                        .from(bottomSheet);

        FloatingActionButton fab =
                findViewById(R.id.fab);

        fab.setOnClickListener(
                new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Snackbar.make(
                        v,
                        "This is a Snackbar",
                        Snackbar.LENGTH_LONG
                ).show();
            }
        });

        Button button =
                findViewById(R.id.button);

        button.setOnClickListener(
                new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                bottomSheetBehavior
                        .setState(
                                BottomSheetBehavior
                                .STATE_EXPANDED
                        );
            }
        });
    }
}

Step 3 — Create strings.xml


<resources>

    <string name="app_name">
        BottomSheet Demo
    </string>

    <string name="dummy_text">
        This is a Bottom Sheet Example.
    </string>

</resources>

How This Example Works

  1. CoordinatorLayout manages view interactions
  2. FloatingActionButton shows Snackbar
  3. Snackbar automatically pushes FAB upward
  4. Button expands Bottom Sheet
  5. BottomSheetBehavior controls sheet states

What Is BottomSheetBehavior?

BottomSheetBehavior controls:

  • Expanded state
  • Collapsed state
  • Hidden state
  • Dragging gestures

Bottom Sheet States

State Description
STATE_EXPANDED Fully visible
STATE_COLLAPSED Partially visible
STATE_HIDDEN Completely hidden
STATE_DRAGGING User dragging sheet
STATE_SETTLING Animating to final state

What Is Snackbar?

Snackbar is a lightweight Material Design message component.

Unlike Toast:

  • Snackbar supports actions
  • Snackbar integrates with CoordinatorLayout
  • Snackbar provides animations

Snackbar Example


Snackbar.make(
    view,
    "Message",
    Snackbar.LENGTH_LONG
).show();

FloatingActionButton Behavior

FloatingActionButton automatically responds to:

  • Snackbar appearance
  • CoordinatorLayout interactions
  • Scrolling behaviors

Modern Android Recommendations

Modern Android applications now commonly use:

  • Material Design 3
  • BottomSheetDialogFragment
  • Jetpack Compose Bottom Sheets
  • Navigation Component
  • ConstraintLayout

Modern Alternative — BottomSheetDialogFragment

Production applications often prefer:


BottomSheetDialogFragment

because it provides:

  • Lifecycle awareness
  • Dialog support
  • Cleaner architecture
  • Better reusability

CoordinatorLayout Advantages

  • Automatic animations
  • Material interactions
  • View coordination
  • Scrolling behaviors
  • Gesture support

Common Beginner Mistakes

1. Using Deprecated Support Libraries

Always prefer:


androidx

instead of:


android.support

2. Forgetting CoordinatorLayout

Snackbar animations and FAB movement require:


CoordinatorLayout

3. Using Fixed Heights Everywhere

Responsive layouts should avoid excessive fixed dimensions.


FAQ

What is the purpose of CoordinatorLayout?

CoordinatorLayout coordinates animations and interactions between child views.


Why does FloatingActionButton move above Snackbar?

CoordinatorLayout automatically adjusts FloatingActionButton position when Snackbar appears.


What is the modern Bottom Sheet solution?

BottomSheetDialogFragment and Jetpack Compose ModalBottomSheet are modern recommended approaches.


Conclusion

CoordinatorLayout, Bottom Sheets, FloatingActionButton, and Snackbar are powerful Material Design components used in modern Android applications.

Together, they create smooth UI interactions, responsive layouts, and modern user experiences.

Modern Android applications should combine Material Design components, lifecycle-aware architecture, and responsive UI systems for scalable production-grade applications.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Tuesday, October 22, 2019

Understanding dp vs px in Android — Screen Density Explained

No comments email this post Edit Post

One of the most important concepts in Android UI development is understanding screen densities and layout scaling.

Android devices come in different:

  • Screen sizes
  • Pixel densities
  • Resolutions
  • Aspect ratios

To create responsive Android applications, developers must understand the difference between:

  • dp (density-independent pixels)
  • px (physical pixels)
  • sp (scale-independent pixels)

What Is dp in Android?

dp stands for:


Density-independent Pixel

It is a virtual pixel unit used for defining:

  • Layout dimensions
  • Margins
  • Paddings
  • View sizes
  • UI positioning

dp ensures that UI elements appear consistently across different Android screen densities.


Why Android Uses dp Instead of px

Different Android devices have different pixel densities.

Example:

  • Low-density screens
  • High-density screens
  • Ultra HD screens

If developers use:


px

directly, UI components may appear:

  • Too small
  • Too large
  • Inconsistent across devices

Using:


dp

solves this problem automatically.


dp Formula

Android converts:


dp → px

using:

:contentReference[oaicite:0]{index=0}

Reverse Formula

To convert:


px → dp

use:

:contentReference[oaicite:1]{index=1}

Example Calculation

Suppose:

  • Screen density = 240 dpi
  • Pixel size = 480 px

Then:

:contentReference[oaicite:2]{index=2}

Result:


320dp

Android Screen Density Buckets

Density DPI Folder
ldpi 120 dpi drawable-ldpi
mdpi 160 dpi drawable-mdpi
hdpi 240 dpi drawable-hdpi
xhdpi 320 dpi drawable-xhdpi
xxhdpi 480 dpi drawable-xxhdpi
xxxhdpi 640 dpi drawable-xxxhdpi

Why Density Buckets Matter

Android automatically loads the appropriate drawable resources depending on device density.

Example:


drawable-hdpi
drawable-xhdpi
drawable-xxhdpi

This ensures:

  • Sharp images
  • Better UI quality
  • Optimized memory usage

Best Practices for Supporting Multiple Screens

1. Use dp Instead of px

Always use:


dp

for:

  • Margins
  • Paddings
  • Layout sizes
  • Button dimensions

2. Use sp for Text Size

Text sizes should use:


sp

instead of:


dp

because sp respects user accessibility font scaling.


3. Use Density-Specific Drawables

Provide images for:


drawable-hdpi
drawable-xhdpi
drawable-xxhdpi

to avoid blurry assets.


4. Avoid Absolute Pixel Sizes

Avoid:


100px

because it breaks UI consistency across devices.


Difference Between dp, px, and sp

Unit Purpose
dp Layout dimensions
px Raw physical pixels
sp Text sizes

Modern Android UI Recommendation

Modern Android applications now commonly use:

  • ConstraintLayout
  • Jetpack Compose
  • Responsive layouts
  • Window size classes
  • Material Design 3

These approaches automatically improve UI adaptability across devices.


Jetpack Compose Example

In Jetpack Compose:


Modifier.size(120.dp)

dp is still the preferred layout unit.


Common Beginner Mistakes

1. Using px Directly

This causes inconsistent UI scaling across devices.


2. Using dp for Text

Always use:


sp

for text sizes.


3. Missing Drawable Variants

Large screens may display blurry images if density-specific assets are missing.


FAQ

Should I ever use px in Android?

Usually no.

Android developers should primarily use:

  • dp for layouts
  • sp for text

What is the baseline Android density?

Android uses:


160 dpi (mdpi)

as the baseline density.


Why use sp for text?

sp supports user font accessibility scaling.


Conclusion

Understanding screen density and layout units is essential for building responsive Android applications.

Using dp and sp correctly ensures that Android applications display consistently across multiple screen sizes and densities.

Modern Android applications should combine responsive layouts, density-aware assets, Material Design principles, and scalable UI systems for production-grade user experiences.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Android and Layout Tutorial — Optimize XML Layouts

No comments email this post Edit Post

Android UI performance is heavily affected by layout hierarchy and view nesting.

Deeply nested layouts can cause:

  • Slow rendering
  • Poor performance
  • Long measure/layout passes
  • Increased memory usage

Android provides:

  • <merge>
  • <include>

to optimize layouts and create reusable UI components efficiently.


What Is <merge> in Android?

The:


<merge>

tag is used for:

  • Reducing unnecessary layout nesting
  • Optimizing view hierarchy
  • Improving rendering performance

When a layout containing:


<merge>

is included inside another layout, the:


<merge>

node itself gets removed and only its child views are added directly to the parent.


Why Use <merge>?

Without:


<merge>

developers often create unnecessary nested layouts such as:


LinearLayout
    └── LinearLayout
            └── Button

Extra nesting increases layout inflation cost.

Using:


<merge>

helps flatten the hierarchy.


Example Without <merge>


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:text="Add"/>

    <Button
        android:text="Delete"/>

</LinearLayout>

Optimized Example Using <merge>


<merge
    xmlns:android=
    "http://schemas.android.com/apk/res/android">

    <Button
        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="@string/add"/>

    <Button
        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="@string/delete"/>

</merge>

How <merge> Works Internally

Suppose:

  • Parent layout includes child layout
  • Child layout root is <merge>

Android removes the:


<merge>

container and directly inserts child views into the parent layout.


Benefits of <merge>

  • Flatter view hierarchy
  • Faster rendering
  • Reduced memory usage
  • Improved UI performance
  • Better layout optimization

What Is <include> in Android?

The:


<include>

tag allows developers to reuse XML layouts across multiple screens.

This helps:

  • Reduce duplicate code
  • Improve maintainability
  • Create reusable UI components
  • Build modular layouts

Why Use <include>?

Many applications reuse:

  • Toolbar layouts
  • Headers
  • Footers
  • Loading layouts
  • Custom sections

Instead of rewriting the same XML repeatedly, developers can reuse layouts using:


<include>

Create Reusable Layout

Example:


res/layout/layout_toolbar.xml

<merge
    xmlns:android=
    "http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="My Toolbar"

        android:textSize="20sp"/>

</merge>

Using <include>


<include

    android:id="@+id/toolbarLayout"

    layout="@layout/layout_toolbar"/>

How <include> Works

  1. Android inflates reusable layout
  2. Included layout inserted into parent
  3. UI components become part of hierarchy

Advantages of <include>

  • Reusable UI
  • Cleaner XML files
  • Easier maintenance
  • Consistent design system
  • Reduced duplication

Using <merge> with <include>

The best optimization pattern is:

  • Reusable layout root = <merge>
  • Parent layout uses <include>

This avoids unnecessary wrapper layouts.


Real-World Example

Reusable toolbar layout:


layout_toolbar.xml

Included in:

  • Home screen
  • Profile screen
  • Settings screen
  • Dashboard screen

Modern Android Recommendations

Modern Android applications now commonly use:

  • ConstraintLayout
  • ViewBinding
  • DataBinding
  • Jetpack Compose
  • Reusable composables

Jetpack Compose Alternative

Jetpack Compose replaces many XML reuse patterns using:


@Composable

functions.


Compose Reusable UI Example


@Composable
fun ToolbarSection() {

    Text(
        text = "Toolbar"
    )
}

When NOT to Use <merge>

Avoid:


<merge>

when:

  • Layout needs its own background
  • Root layout attributes are required
  • Standalone inflation is needed

Common Beginner Mistakes

1. Deeply Nested Layouts

Too many nested layouts reduce rendering performance.


2. Forgetting Root Layout Requirements

<merge> removes the root node entirely.


3. Duplicating XML Repeatedly

Reusable components should use:


<include>

Performance Benefits

Without Optimization With merge/include
Deep hierarchy Flat hierarchy
Slower rendering Faster rendering
Duplicate XML Reusable layouts
More memory usage Optimized memory usage

FAQ

What is <merge> in Android?

<merge> removes unnecessary layout wrappers and optimizes hierarchy.


What is <include> used for?

<include> allows reusing XML layouts across multiple screens.


Can merge and include be used together?

Yes. Using them together provides excellent layout optimization.


Conclusion

<merge> and <include> are powerful Android XML optimization tools that improve performance and maintainability.

They help developers create reusable layouts, reduce hierarchy depth, and optimize rendering performance in Android applications.

Modern Android applications should combine optimized layouts, AndroidX, ViewBinding, ConstraintLayout, and scalable UI architecture for production-grade performance.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Tuesday, October 15, 2019

Android ConstraintLayout Tutorial — Build Responsive Modern UI

No comments email this post Edit Post

ConstraintLayout is one of the most powerful and flexible layout systems in Android development.

Google introduced ConstraintLayout to solve common UI problems such as:

  • Deeply nested layouts
  • Poor rendering performance
  • Complex responsive UI structures
  • Slow layout inflation

ConstraintLayout helps developers create flat, flexible, and responsive Android user interfaces with better performance.


What Is ConstraintLayout?

ConstraintLayout is a ViewGroup that allows positioning and sizing views using constraints relative to:

  • Parent layout
  • Other views
  • Guidelines
  • Chains

It is now the recommended XML layout system for Android applications.


Why Use ConstraintLayout?

Older Android layouts often required:

  • Nested LinearLayouts
  • Complex RelativeLayouts
  • Multiple wrappers

This increased:

  • Rendering cost
  • Memory usage
  • Layout complexity

ConstraintLayout solves these problems with a flat hierarchy.


Benefits of ConstraintLayout

  • Flat view hierarchy
  • Better performance
  • Flexible positioning
  • Responsive UI design
  • Reduced nesting
  • Powerful design editor support

Modern Android Studio Requirement

Modern Android development should use:

  • Latest Android Studio
  • AndroidX libraries
  • ConstraintLayout 2.x+

Modern ConstraintLayout Dependency

Inside:


build.gradle

Add:


implementation
'androidx.constraintlayout:constraintlayout:2.1.4'

Important Modernization

Older tutorials use:


android.support.constraint.ConstraintLayout

which is deprecated.

Modern Android applications should use:


androidx.constraintlayout.widget.ConstraintLayout

Basic ConstraintLayout Example


<?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"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="ConstraintLayout Example"

        android:layout_marginStart="16dp"

        android:layout_marginTop="16dp"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Understanding Constraints

ConstraintLayout positions views using:


constraints

A view must usually have:

  • Horizontal constraint
  • Vertical constraint

Common Constraint Attributes

Attribute Purpose
layout_constraintStart_toStartOf Align start edge
layout_constraintEnd_toEndOf Align end edge
layout_constraintTop_toTopOf Align top edge
layout_constraintBottom_toBottomOf Align bottom edge

Example — Center View Horizontally


app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"

Example — Center View Vertically


app:layout_constraintTop_toTopOf="parent"

app:layout_constraintBottom_toBottomOf="parent"

ConstraintLayout Visualization

Each view behaves like a node connected through constraints.

ConstraintLayout automatically calculates positions dynamically.


Why ConstraintLayout Improves Performance

ConstraintLayout reduces:

  • Nested layouts
  • Measure passes
  • Layout inflation overhead
  • Rendering complexity

Flat hierarchies improve UI performance significantly.


Using Match Constraints

Instead of:


match_parent

ConstraintLayout often uses:


0dp

which means:


Match Constraints

Example — Match Constraints


android:layout_width="0dp"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"

What Are Chains?

Chains allow multiple views to behave like a single group.

Useful for:

  • Even spacing
  • Horizontal alignment
  • Vertical alignment

Chain Styles

  • Spread
  • Spread Inside
  • Packed

What Are Guidelines?

Guidelines are invisible helper lines used for positioning views consistently.


Guideline Example


<androidx.constraintlayout.widget.Guideline

    android:id="@+id/guideline"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:orientation="vertical"

    app:layout_constraintGuide_percent="0.5"/>

What Are Barriers?

Barriers dynamically align views based on the largest referenced view.

Useful for:

  • Dynamic content
  • Localization
  • Responsive layouts

Design Editor Support

Android Studio provides a powerful visual editor for ConstraintLayout.

Features:

  • Drag-and-drop constraints
  • Visual blueprint mode
  • Constraint handles
  • Live previews

ConstraintLayout vs LinearLayout

LinearLayout ConstraintLayout
Simple rows/columns Flexible positioning
Nested layouts required Flat hierarchy
Less efficient for complex UI Better performance

ConstraintLayout vs RelativeLayout

RelativeLayout ConstraintLayout
Older positioning system Modern flexible constraints
Less optimization Better performance
Limited tools Advanced editor support

Modern Android Recommendations

Modern Android applications commonly use:

  • ConstraintLayout
  • ViewBinding
  • MotionLayout
  • Material Design 3
  • Jetpack Compose

What Is MotionLayout?

MotionLayout is built on top of ConstraintLayout and supports:

  • Animations
  • Transitions
  • Gesture-based UI
  • Complex motion systems

Jetpack Compose Alternative

Jetpack Compose now provides declarative UI systems that reduce XML dependency.

However, ConstraintLayout is still widely used in XML-based Android projects.


Common Beginner Mistakes

1. Missing Constraints

Views without constraints may appear incorrectly positioned.


2. Overusing Nested Layouts

ConstraintLayout is designed to reduce nesting.


3. Using match_parent Incorrectly

Prefer:


0dp

for match constraints.


Best Practices

  • Use flat hierarchies
  • Prefer ConstraintLayout for complex screens
  • Use guidelines for consistency
  • Use chains for grouped alignment
  • Combine with ViewBinding

FAQ

Why is ConstraintLayout recommended?

ConstraintLayout improves performance and supports flexible UI design.


Is ConstraintLayout still used?

Yes. It is still widely used in XML-based Android applications.


What is the modern alternative?

Jetpack Compose is the modern declarative UI toolkit for Android.


Conclusion

ConstraintLayout is one of the most powerful Android UI systems for building responsive and optimized layouts.

It reduces nesting, improves rendering performance, and provides flexible positioning capabilities for modern Android applications.

Modern Android development should combine ConstraintLayout, AndroidX, Material Design, responsive layouts, and scalable architecture for production-grade UI systems.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.