Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 104 ยท Legacy Views

More View Components: Toast, CardView, TableLayout, Autosizing Text and Nested Lists

Fill the gaps of the XML view toolkit: custom Toast, CardView and expandable cards, ScrollView variants, TableLayout, autosizing TextView, ToggleButton, nested RecyclerView, scaling to screen sizes and ActionBar versus Toolbar.

The lessons on view widgets, XML layouts and RecyclerView cover the core of the View system. Real XML projects also use a handful of extra components that tutorials meet one by one: custom Toasts, CardView, the scroll-view family, TableLayout, autosizing text, toggle buttons, a RecyclerView inside a RecyclerView, and the confusing trio ActionBar, Toolbar and AppBar. This lesson puts them in one place, shows the read-only Android code and tests the logic that is yours in runnable Kotlin.

Toast: a short message

A Toast is a small, non-interactive pop-up that disappears by itself. It is the simplest feedback tool and it needs a Context.

Kotlin
// read-only example: basic Toast
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show()    // about 2 seconds
Toast.makeText(this, "Upload finished", Toast.LENGTH_LONG).show()   // about 3.5 seconds

Position and look:

  • setGravity(gravity, xOffset, yOffset) moves a Toast, but for text Toasts in apps that target Android 11 (API 30) or higher the call is ignored and the system chooses the position. Code such as Toast.makeText(...).apply { setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, 0, 120) } is legacy.
  • Custom layouts (setView) are deprecated since API 30, and apps targeting API 30+ cannot show custom Toast views while in the background. If you need a styled message with an icon, an action or a color, use a Snackbar (see Menus and dialogs) or an in-app banner instead.
  • A Toast does not belong to your screen: it can stay visible after the Activity closes. Do not show important information or errors that need a decision in a Toast.

In Compose there is no Toast API; you either call the same Toast.makeText or, better, show a Snackbar through the SnackbarHostState (Scaffold and app bars). Third-party libraries that offer "styled" or "colored" toasts mostly wrap a custom view, so they have the same restriction on new API levels.

CardView and expandable cards

CardView (and the Material version, MaterialCardView) is a FrameLayout with rounded corners, elevation and a background, a quick way to make "card" rows.

XML
<!-- read-only example: a Material card -->
<com.google.android.material.card.MaterialCardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:cardCornerRadius="12dp"
    app:cardElevation="4dp"
    app:strokeWidth="1dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">
        <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" />
        <TextView android:id="@+id/details" android:layout_width="match_parent" android:layout_height="wrap_content" android:visibility="gone" />
    </LinearLayout>
</com.google.android.material.card.MaterialCardView>

An expandable card hides the details view (visibility="gone") and toggles it when the card is clicked. Add android:animateLayoutChanges="true" on the parent, or call TransitionManager.beginDelayedTransition(parent) before changing visibility, to animate the change. The part that matters in a list is where the expanded state lives: a recycled row must not remember "expanded" for the wrong item, so keep the flag in your data model, not in the view.

Kotlin Expandable card state in a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Because the flag is in the data, a recycled row can be bound correctly: details.isVisible = item.expanded in onBindViewHolder (RecyclerView).

The scroll views

  • ScrollView scrolls one child vertically. The child is usually a vertical LinearLayout. Wrong for long lists, because it creates all children at once.
  • NestedScrollView does the same and also takes part in nested scrolling with the CoordinatorLayout (collapsing toolbars, bottom sheets). Use it instead of ScrollView whenever a scrolling container sits inside such a parent.
  • HorizontalScrollView scrolls one child horizontally; for many items prefer a horizontal RecyclerView.
  • Put android:fillViewport="true" on the scroll view if its content is shorter than the screen and should still stretch.

Never put a ListView or a vertical RecyclerView of unknown size inside a ScrollView without thought: the inner list is measured at full height, loses recycling and scrolls badly. Use one RecyclerView with several view types, or a ConcatAdapter.

TableLayout and AbsoluteLayout

TableLayout arranges children into rows (<TableRow>) and columns, like an HTML table. Columns take their width from the widest cell. Useful attributes: android:stretchColumns="1" makes column 1 fill the remaining width, android:shrinkColumns, and android:layout_span on a cell to span columns.

XML
<!-- read-only example: a small form table -->
<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1">
    <TableRow>
        <TextView android:text="Name" />
        <EditText android:id="@+id/name" android:hint="Ada" />
    </TableRow>
    <TableRow>
        <TextView android:text="Email" />
        <EditText android:id="@+id/email" android:inputType="textEmailAddress" />
    </TableRow>
</TableLayout>

Today a ConstraintLayout or a GridLayout does the same with a flatter hierarchy, and in Compose you would use Row and Column or a Layout. AbsoluteLayout places children at exact x and y pixel positions. It has been deprecated since API 3 and breaks on every screen size except the one you tested, so you only need to recognize it in very old code. The reason it failed is the lesson: positions must be relative to the container or in density-independent units.

Scaling to different screen sizes

A layout should adapt, not scale. The tools, from simplest to most flexible:

  1. dp and sp, not px. 1 dp is one pixel at 160 dpi; the system converts. Text uses sp so it respects the user's font size.
  2. Flexible containers. match_parent, wrap_content, weight in a LinearLayout, constraints and percentage guidelines in a ConstraintLayout (app:layout_constraintGuide_percent="0.4", app:layout_constraintWidth_percent="0.5").
  3. Resource qualifiers. layout-sw600dp/ loads on screens with a smallest width of at least 600 dp (a tablet), layout-land/ for landscape, and values-sw600dp/dimens.xml can change spacing.
  4. Window size classes (compact, medium, expanded) in Compose (Adaptive layouts).

The qualifier lookup is a "pick the best match" rule you can model: among all qualifiers whose condition is true for the device, choose the most specific one.

Kotlin Which layout folder wins?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The real algorithm eliminates qualifiers in a fixed priority order, but the observable result for this common case is the same: the most specific folder that fits.

Autosizing TextView

A TextView can shrink or grow its text to fill its box, which helps with titles of unknown length. Since API 26 (and through TextViewCompat or AppCompat for older versions) you enable it in XML:

XML
<!-- read-only example: uniform autosizing -->
<TextView
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:text="A headline of unknown length"
    android:maxLines="2"
    android:autoSizeTextType="uniform"
    android:autoSizeMinTextSize="12sp"
    android:autoSizeMaxTextSize="32sp"
    android:autoSizeStepGranularity="2sp" />

The view tries sizes from the minimum to the maximum in steps and picks the largest size that fits. The same idea in Compose needs a loop with onTextLayout or the BasicText autoSize parameter in newer versions. The search is easy to model with a fake measurement (text width grows linearly with size):

Kotlin Autosize: the largest text size that fits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

ToggleButton, Switch and Chip

ToggleButton is a button with two states and text for each (android:textOn, android:textOff) and isChecked. It is the old way to say "on/off": prefer a SwitchMaterial for settings and a Chip or MaterialButtonToggleGroup for choices, which look current and respond to the Material theme (View widgets). The listener is the same OnCheckedChangeListener as for a CheckBox. In an alarm app a toggle per weekday is a typical use.

Nested RecyclerView

A screen such as a streaming home page has rows inside a vertical list: each row is a horizontal list. The recipe: a parent RecyclerView with a vertical LinearLayoutManager, whose ViewHolder contains a child RecyclerView with a horizontal manager and its own adapter.

Kotlin
// read-only example: the parent adapter creates one child list per row
class ParentAdapter(private val rows: List<Row>) : RecyclerView.Adapter<ParentAdapter.VH>() {
    private val sharedPool = RecyclerView.RecycledViewPool()      // children share recycled views

    inner class VH(val binding: ItemRowBinding) : RecyclerView.ViewHolder(binding.root) {
        init {
            binding.children.layoutManager = LinearLayoutManager(binding.root.context, RecyclerView.HORIZONTAL, false)
            binding.children.setRecycledViewPool(sharedPool)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        VH(ItemRowBinding.inflate(LayoutInflater.from(parent.context), parent, false))

    override fun onBindViewHolder(holder: VH, position: Int) {
        holder.binding.title.text = rows[position].title
        holder.binding.children.adapter = ChildAdapter(rows[position].items)
    }

    override fun getItemCount() = rows.size
}

Three tricks keep it smooth: share one RecycledViewPool, set the child layout manager once in the holder (not in each bind), and remember each child's scroll position so scrolling a row away and back restores it. In Compose the equivalent is a LazyColumn containing LazyRows, with scroll state kept by rememberLazyListState per row (Lazy lists and grids).

ActionBar, Toolbar and AppBar

These words describe three layers of the same top-of-screen UI:

Name What it is Notes
ActionBar The original top bar the system gives your Activity through its theme Fixed at the top, limited customization; removed by Theme.*.NoActionBar
Toolbar A View you put anywhere in your layout, then register with setSupportActionBar(toolbar) Flexible: color, height, scrolling, can host a search field
AppBar The concept and container: in Material it is the AppBarLayout (or MaterialToolbar) holding the title, navigation icon and actions In Compose: TopAppBar

So a Toolbar can act as the ActionBar. The standard modern setup is: a NoActionBar theme, an AppBarLayout containing a MaterialToolbar, and setSupportActionBar. Menus are the same either way (Menus and dialogs), and the Compose version is in Scaffold and app bars.

Material button polish: FAB theming and ripples

  • Floating action button: FloatingActionButton (circular) and ExtendedFloatingActionButton (icon plus text, can shrink/extend with shrink() and extend() while scrolling). Change colors with app:backgroundTint and shape with the shapeAppearance attribute (cornerFamily, cornerSize), or set a style once in the theme through floatingActionButtonStyle.
  • Ripple: the touch feedback of Material buttons comes automatically. On a plain view add android:background="?attr/selectableItemBackground" (or selectableItemBackgroundBorderless for an icon). A custom shape with a ripple wraps the shape in a <ripple android:color="..."> drawable (Resources).
  • A Snackbar normally slides over a FAB: put both inside a CoordinatorLayout, and the FAB moves up automatically.

Common mistakes

  • Using a Toast for errors that need action.
  • Keeping "expanded" or "checked" state only in a recycled view.
  • A RecyclerView inside a ScrollView.
  • Hard-coded pixel positions or sizes.
  • Calling setGravity on a Toast and expecting it to work on new API levels.
  • Setting a child LayoutManager in every onBindViewHolder, which is slow and resets the scroll position.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the expanded state of a card in a RecyclerView be stored?

    Views are recycled, so state kept in a view would show on the wrong row. Keep it in data and bind it.
  2. 2. Which container takes part in nested scrolling with a CoordinatorLayout?

    NestedScrollView supports the nested-scrolling protocol that collapsing toolbars and bottom sheets rely on.
  3. 3. What does a layout-sw600dp folder mean?

    sw means smallest width. The qualifier is true on any device whose shortest side is 600 dp or more, such as most tablets.
  4. 4. How are ActionBar and Toolbar related?

    setSupportActionBar(toolbar) makes your Toolbar behave as the Activity's ActionBar, with menus and navigation icon.

Summary

  • Toasts are brief and non-interactive; positioning and custom views are limited on new API levels, so use Snackbars for rich messages.
  • CardView/MaterialCardView makes cards; keep expansion state in data.
  • NestedScrollView for coordinated scrolling, TableLayout for grids of rows, and never AbsoluteLayout.
  • Adapt to screens with dp/sp, flexible constraints, sw qualifiers and window size classes.
  • Autosizing TextView picks the largest size that fits; nested lists share a recycled view pool.
  • ActionBar is the system bar, Toolbar is a view that can replace it, AppBar is the Material container concept.

Next: Views and Compose side by side.