Android SharedPreferences Tutorial and Example

Adding a FloatingActionButton with Snackbar in Android Apps

Press the plus button in a shopping app and the screen should confirm it immediately. A Snackbar sliding up from the bottom edge with "Added to trolley" is the pattern shoppers now expect from Coles and Woolworths apps, and Australian banking apps use the same pattern when a transfer clears. A FloatingActionButton paired with a Snackbar gives your Android project that same polished feedback loop, and it takes surprisingly little code.

This walkthrough builds the combination from scratch. You will add Google's Material Components library, place a FloatingActionButton inside a CoordinatorLayout, and trigger a Snackbar from its click listener. The important part is the anchor: when the button lives in a CoordinatorLayout, the Snackbar knows about it, so the message pushes the button up instead of hiding behind it.

You need Android Studio with a working project, a device or emulator running Android 5.0 (API 21) or later, and a basic familiarity with Kotlin or Java and Gradle. If you have never used the Material library, start here, because both the button and the Snackbar live in it. Older tutorials that reference the old com.android.support packages will not compile on a current project, so stick with AndroidX and Material 1.x.

The sample project is a small order-taking app for a café in Fitzroy, Melbourne. Customers tap the button to add a flat white, the Snackbar confirms the addition and offers an undo, and the list below updates. The same code suits a fitness tracker for a gym in Bondi, a booking app for a physio in South Bank, or a note tool for a tradie working across Brisbane.

Adding the Material Components dependency

The FloatingActionButton and Snackbar classes ship in the Material library, not in AndroidX core, so declare it in your app-level build.gradle file.

dependencies {
    implementation("androidx.appcompat:appcompat:1.7.0")
    implementation("com.google.android.material:material:1.12.0")
}

Sync the project after editing, and check that your theme inherits from a Material parent such as Theme.Material3.DayNight.NoActionBar or Theme.MaterialComponents.DayNight.NoActionBar. Without a Material theme, the button renders as a plain circle with the wrong elevation and shadow, and the Snackbar loses its rounded corners and colour treatment.

Version numbers move quickly, so read the release notes rather than copying old build files from a blog post. If your project uses a Jetpack Compose setup instead of views, this particular guide does not apply, since the Compose equivalent relies on a Scaffold and a SnackbarHost.

Choosing a CoordinatorLayout for the anchor

A CoordinatorLayout gives the Snackbar its anchor behaviour. It watches its children and relocates the Snackbar and the FloatingActionButton so they never overlap, which means your "Added to trolley" message does not sit on top of the plus button at the bottom of the screen.

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.MaterialToolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize" />
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <!-- your list of orders -->
    </androidx.core.widget.NestedScrollView>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fabAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="16dp"
        app:srcCompat="@drawable/ic_add" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

ConstraintLayout works too, but the Snackbar then attaches to the bottom of the window and can cover the button. If you must stay with ConstraintLayout, set the anchor explicitly with Snackbar.setAnchorView(fabAdd) so the behaviour stays predictable.

Declaring the FloatingActionButton in XML

The button above uses app:srcCompat rather than android:src, which lets vector drawables render correctly on older devices. Tint the icon with app:tint, set app:backgroundTint for the container colour, and always supply a contentDescription so TalkBack announces something useful like "Add order".

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fabAdd"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    android:contentDescription="@string/add_order"
    app:backgroundTint="@color/brand_primary"
    app:tint="@color/white"
    app:srcCompat="@drawable/ic_add" />

Australian apps often follow the platform guidance on 56dp circles and a 16dp margin from the screen edge. Keep the description specific: "Add order" is far better than "Button". If your icon is a plus sign, remember that shape alone carries meaning for sighted users but not for anyone using a screen reader.

Showing a Snackbar from the button click

The Snackbar is created with the button's view as the first argument. Because that view lives inside the CoordinatorLayout, the Snackbar anchors to it automatically and lifts the button while the message is on screen.

fabAdd.setOnClickListener { view ->
    Snackbar.make(view, getString(R.string.order_added), Snackbar.LENGTH_LONG)
        .setAction(R.string.undo) { removeLastOrder() }
        .show()
}

In Java the same call reads Snackbar.make(view, getString(R.string.order_added), Snackbar.LENGTH_LONG). The Java and Kotlin APIs are identical, since Material ships both flavours of every class.

Move all user-facing strings into strings.xml, including the action label, and use plurals for counts so "1 item added" and "3 items added" read naturally. Keep the message short enough to fit on one line on a compact screen, or call setTextMaxLines(2) when you have more to say.

Handling the action and dismissal

The undo action is the reason to prefer a Snackbar over a Toast. The action label takes a click listener, so you can remove the row you just added and refresh the list without the customer losing their place.

If you need to know when the message disappears, attach a callback.

val snackbar = Snackbar.make(view, R.string.order_added, Snackbar.LENGTH_LONG)
snackbar.setAction(R.string.undo) { removeLastOrder() }
snackbar.addCallback(object : Snackbar.Callback() {
    override fun onDismissed(sb: Snackbar, event: Int) {
        // save state or log the interaction
    }
})
snackbar.show()

The callback distinguishes a timeout dismissal from a swipe or a programmatic dismiss, which matters if you record analytics. Durations come from LENGTH_SHORT and LENGTH_LONG, and there is no built-in indefinite option, so avoid LENGTH_INDEFINITE unless you also wire up a timeout yourself.

Comparing your feedback options

Different feedback patterns carry different trade-offs for a user checking a phone on the tram through Melbourne's CBD or standing in a queue at a Woolworths checkout.

Option Lifetime Action button Blocks the UI Best fit
Snackbar Short, dismissible Yes No Confirming an action near a button
Toast Short, fades out No No Background status messages
AlertDialog Until answered Yes Yes Decisions that need confirmation
Inline banner Until removed Sometimes No Persistent status on a screen

A Snackbar wins when the message follows a tap on the FloatingActionButton, because the proximity tells the user which control caused it. A dialog would interrupt the flow of ordering another coffee, which is exactly what most apps should avoid.

Styling the Snackbar and the button

Colours come from your theme or from direct calls on the Snackbar object.

Snackbar.make(view, R.string.order_added, Snackbar.LENGTH_LONG)
    .setBackgroundTint(R.color.snackbar_background)
    .setTextColor(R.color.snackbar_text)
    .setActionTextColor(R.color.brand_accent)
    .setDuration(Snackbar.LENGTH_LONG)
    .show()

Define those colours in res/values/colors.xml and provide a values-night variant if you ship a dark theme. Australian users often prefer a dark-mode app that mirrors the system setting, and Material's DayNight themes handle most of that work once the custom colours are defined for both modes.

You can also swap in a custom Snackbar layout with setView() when you need extra content, such as an undo icon beside the label. The default styling, rounded corners, and elevation usually look right, so custom layouts are best reserved for genuinely different content.

Testing on a real device and avoiding common pitfalls

Run the app on a physical handset rather than trusting the emulator alone. Test a small screen, a tablet layout, a dark theme, and a screen reader. Rotation and process death are common trouble spots, so store the pending undo action in saved state if the message matters.

The classic mistakes are showing a Snackbar from a background thread, which crashes the app, and forgetting that the Snackbar needs a CoordinatorLayout to anchor correctly. Another is using Toast for anything the user should be able to act on, since a Toast vanishes before a hurried tap in a Woolies self-checkout can land.

The last pitfall is over-designing. One clear Snackbar with an undo action is enough. Plenty of local apps, from Telstra MyView to ANZ's transaction screens, keep it simple, and matching that restraint is usually the smarter choice.