Android SharedPreferences Tutorial and Example

Using CardView for modern Android card layouts

CardView groups content on a raised surface, giving Android screens the layered appearance associated with Material Design. The classic androidx.cardview.widget.CardView suits small apps and tutorials, while MaterialCardView adds current ripple, outline, and selection behaviour. Both can contain text, images, buttons, or a short form.

This example follows an event guide for Sydney and Melbourne. It uses Australian English, DD/MM/YYYY dates, A$ prices shown as GST-inclusive, and content suitable for the Australian Google Play market. These choices affect the sample data rather than the reusable layout, so the card structure also works for retail, transport, banking, and community apps.

Adding CardView to an Android project

Open your app module’s build.gradle.kts file and add the card, list, and Material dependencies:

dependencies {
    implementation("androidx.cardview:cardview:1.0.0")
    implementation("androidx.recyclerview:recyclerview:1.3.2")
    implementation("com.google.android.material:material:1.12.0")
}

The card library supplies the basic rounded container, while RecyclerView handles long collections of cards efficiently. The Material dependency is required for MaterialCardView; it can be omitted when the project uses only the classic CardView implementation.

Use the namespace declared by each library when referring to its attributes. Card dimensions and spacing should normally use dp, while text sizes use sp so they respect the user’s font-size preference.

Creating a card layout

Create res/layout/item_event_card.xml and place a CardView around a simple vertical content structure. Give the card and its text fields stable IDs so an adapter can populate them later.

<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/eventCard"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="12dp"
    android:clickable="true"
    android:focusable="true"
    app:cardCornerRadius="12dp"
    app:cardElevation="3dp"
    app:cardUseCompatPadding="true">

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

        <TextView
            android:id="@+id/eventName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Sydney Harbour sunset walk"
            android:textColor="?attr/colorOnSurface"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/eventMeta"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="6dp"
            android:text="Sat 14/06/2025, 5:30 PM"
            android:textColor="?attr/colorOnSurfaceVariant" />

        <TextView
            android:id="@+id/eventPrice"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="A$18, GST included"
            android:textColor="?attr/colorPrimary"
            android:textStyle="bold" />
    </LinearLayout>
</androidx.cardview.widget.CardView>

The inner LinearLayout owns the padding, allowing the CardView to remain focused on the surface, corners, and shadow. A more complex card could use ConstraintLayout, but the vertical arrangement is easier to maintain when cards contain a heading, metadata, and one key detail.

Styling cards for a consistent interface

Card colours should come from theme resources rather than fixed values. colorSurface and colorOnSurface provide sensible light and dark theme combinations, while colorPrimary can highlight a price or action. The cardUseCompatPadding attribute adds compatible spacing for shadows on older Android releases.

The classic CardView does not provide a visible outline. For an outlined treatment, change the root class to com.google.android.material.card.MaterialCardView and add Material attributes such as app:strokeWidth="1dp" and app:strokeColor="?attr/colorOutline". The remaining content and adapter code can stay unchanged.

On macOS, developers comparing several XML variants can pair Android Studio with the MagikMacs editor, while using the preview and accessibility tools as the visual checks. Keeping shared dimensions in resources also makes these variations consistent.

Showing cards with RecyclerView

A RecyclerView reuses card rows instead of rebuilding the entire screen, making it suitable for event lists, product catalogues, and news feeds. Each row inflates the same card layout, and the adapter replaces its text whenever a new item is bound.

Define a small model and an adapter that finds the required views:

data class Event(
    val title: String,
    val details: String,
    val price: String
)

class EventAdapter(
    private val events: List<Event>,
    private val onEventClick: (Event) -> Unit
) : RecyclerView.Adapter<EventAdapter.EventHolder>() {

    inner class EventHolder(itemView: View) :
        RecyclerView.ViewHolder(itemView) {

        private val titleView =
            itemView.findViewById<TextView>(R.id.eventName)
        private val detailsView =
            itemView.findViewById<TextView>(R.id.eventMeta)
        private val priceView =
            itemView.findViewById<TextView>(R.id.eventPrice)

        fun bind(event: Event) {
            titleView.text = event.title
            detailsView.text = event.details
            priceView.text = event.price
            itemView.setOnClickListener { onEventClick(event) }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EventHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_event_card, parent, false)
        return EventHolder(view)
    }

    override fun onBindViewHolder(holder: EventHolder, position: Int) {
        holder.bind(events[position])
    }

    override fun getItemCount() = events.size
}

Place a RecyclerView in the activity layout, assign a LinearLayoutManager, and attach the adapter. Australian sample data can include a Sydney walking event and a Melbourne market event, with prices and dates supplied by the data layer rather than embedded in the XML.

Handling taps and selection states

The standard CardView does not automatically provide Material’s pressed ripple. Use MaterialCardView when consistent touch feedback is important, or supply a compatible selectable background for the classic view. Set the card’s click listener to the row action so the entire surface responds to a tap without making its text individually interactive.

MaterialCardView also supports a checkable mode through android:checkable="true". This suits filter cards or single-choice categories where the selected state must remain visible. A checked icon and a distinct stroke can communicate that state, although colour must not be the only indicator.

Accessibility depends on readable content and predictable focus. Decorative images should use a null content description, while meaningful images need a concise description. Interactive cards must provide a touch target of at least 48dp, and child buttons should perform different actions from the surrounding card.

Combining cards with other layouts

Cards work well within constrained layouts, but nested scrolling containers require care. A RecyclerView should remain the main scrolling element when it contains cards; wrapping it in a NestedScrollView can create unpredictable measurement and scrolling behaviour. A NestedScrollView is reasonable for a small, static group of cards that never changes.

GridLayoutManager can display cards in two or more columns on larger phones and tablets. Changing the span count according to available width gives each card enough space for Australian addresses, event details, and prices without squeezing the content. Images inside cards should retain their aspect ratio with adjustViewBounds.

Avoid placing clickable cards inside another clickable card, since competing touch targets can confuse users. A card should represent one action or one content item, with any secondary buttons clearly separated from the card’s primary destination.

Preparing cards for release

Build the application against a DayNight theme and provide suitable values-night colours. Test both light and dark modes, along with larger font settings and display scaling. Material themes expose semantic attributes that allow the same card layout to adapt without maintaining separate dark-theme XML files.

ViewBinding can remove repeated findViewById calls, while vector drawables and restrained shadows help limit rendering overhead on lower-powered Android devices. CardView creates a shadow layer, so stacking many cards or adding several background effects increases overdraw. Inspect the layout in Android Studio’s Layout Inspector when scrolling feels inefficient.

Before publishing through Google Play in Australia, verify currency formatting, GST-inclusive pricing, Australian English, and date presentation. Test the complete flow with TalkBack, rotation, slow network conditions, and the range of phone and tablet screen sizes used by the target audience. CardView remains effective for restrained, content-led interfaces, while MaterialCardView provides the stronger default for new projects requiring current interaction states.