Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 104 ยท Legacy Views

Classic Views and Widgets: TextView, EditText, Spinner and More

Use the classic Android widgets: TextView, EditText and TextInputLayout, Button, Spinner, CheckBox, RadioGroup, Switch, SeekBar, RatingBar, ProgressBar and ImageView, with Compose equivalents.

A widget is a ready-made View that draws something and reacts to the user: a label, a text field, a checkbox, a slider. The View system ships dozens of them in android.widget, and Material Components adds themed versions in com.google.android.material. You declare them in XML, find them with ViewBinding and attach listeners in code.

This lesson covers the widgets almost every XML app uses, how to read their values, and what you write in Compose instead. Android code and XML are read-only here, because they need the Android SDK. The TryIts are plain Kotlin stand-ins that model the listener pattern, form validation and value mapping, and each one says what it replaces. If you have not read it yet, start with XML Layouts and the ViewBinding section of Views Interop.

The listener pattern

Every interactive widget reports changes through a listener: an object (usually a lambda) you register with the view. Button has setOnClickListener, CheckBox has setOnCheckedChangeListener, SeekBar has setOnSeekBarChangeListener and so on. The view calls your code when the event happens. State lives inside the view (a text field remembers its text), and you read it or push new values with setters. That is the main difference from Compose, where the state lives in your code and the widget only displays it.

The stand-in below builds a tiny widget with a listener list and shows both directions of the flow: the user changes a value, listeners run, and code sets a value back.

Kotlin Widgets with listeners (stand-in)

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.

TextView

TextView shows text and is the base class of EditText and Button. Common attributes are text, textSize (in sp), textColor, textStyle (bold, italic), maxLines with ellipsize="end", and textAppearance, which applies a Material text style from your theme. Always put visible strings in res/values/strings.xml and reference them with @string/..., as in Manifest and Resources.

XML
<!-- read-only example -->
<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/welcome"
    android:textAppearance="?attr/textAppearanceHeadlineSmall"
    android:maxLines="2"
    android:ellipsize="end" />
Kotlin
// read-only example
binding.title.text = getString(R.string.welcome_user, user.name)
binding.link.movementMethod = LinkMovementMethod.getInstance() // to make links clickable

For links and styled text, android:autoLink="web" finds URLs and HtmlCompat.fromHtml(...) renders simple HTML. In Compose this is Text(...) (see Text, Images and Icons).

EditText and TextInputLayout

EditText is an editable TextView. inputType selects the keyboard and the behavior (textEmailAddress, number, textPassword, textMultiLine), and imeOptions sets the keyboard action button (actionNext, actionDone).

With Material Components you wrap the field in a TextInputLayout, which adds a floating label, a helper text, an error message, an icon and a password toggle:

XML
<!-- read-only example -->
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/emailLayout"
    style="@style/Widget.Material3.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/email">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/emailInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:imeOptions="actionNext" />
</com.google.android.material.textfield.TextInputLayout>
Kotlin
// read-only example
binding.emailInput.doAfterTextChanged { text ->
    val valid = Patterns.EMAIL_ADDRESS.matcher(text.toString()).matches()
    binding.emailLayout.error = if (valid || text.isNullOrEmpty()) null else getString(R.string.invalid_email)
}

doAfterTextChanged comes from androidx.core.widget (core-ktx). The Compose equivalents are OutlinedTextField and TextField with isError and supportingText, as in Inputs and Forms. The stand-in below validates a form the way a TextWatcher would, with errors per field.

Kotlin Form validation like a TextWatcher (stand-in)

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.

Button and its relatives

Button triggers an action in setOnClickListener. Material provides MaterialButton (filled by default, with style="@style/Widget.Material3.Button.OutlinedButton" or TextButton variants and an icon), FloatingActionButton, ExtendedFloatingActionButton and MaterialButtonToggleGroup for a segmented control. Disable a button with isEnabled = false while a request is running so the user cannot send it twice. In Compose you will use Button, OutlinedButton, TextButton and FloatingActionButton.

Spinner (drop-down)

Spinner is the classic drop-down list. An adapter supplies the items, and OnItemSelectedListener reports the choice. With Material 3 the recommended replacement is an exposed dropdown menu: a TextInputLayout with the ExposedDropdownMenu style that contains a MaterialAutoCompleteTextView.

Kotlin
// read-only example
val countries = resources.getStringArray(R.array.countries)
binding.countrySpinner.adapter =
    ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, countries)

binding.countrySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
    override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
        viewModel.selectCountry(countries[position])
    }
    override fun onNothingSelected(parent: AdapterView<*>) = Unit
}

The Compose version is ExposedDropdownMenuBox with a DropdownMenu, with the selected value held in a remember or ViewModel state.

CheckBox, RadioGroup and Switch

  • CheckBox is an independent yes/no choice (isChecked).
  • RadioGroup contains several RadioButtons of which only one can be selected; checkedRadioButtonId or setOnCheckedChangeListener tells you which. Give each button an id.
  • SwitchMaterial / MaterialSwitch is an on/off setting that takes effect immediately, like a light switch. Use a checkbox when the choice is applied later (with a "Save" button).
Kotlin
// read-only example
binding.sizeGroup.setOnCheckedChangeListener { _, checkedId ->
    val size = when (checkedId) {
        R.id.sizeSmall -> "S"
        R.id.sizeMedium -> "M"
        R.id.sizeLarge -> "L"
        else -> null
    }
    viewModel.setSize(size)
}
binding.notifySwitch.setOnCheckedChangeListener { _, isChecked -> viewModel.setNotify(isChecked) }

In Compose: Checkbox, RadioButton (with Modifier.selectableGroup() on the container) and Switch, all driven by state you own.

SeekBar and Slider

SeekBar selects an integer from 0 to max (there is no minimum below API 26, where min was added). onProgressChanged fires for every change, and its fromUser flag tells you if the user or your code caused it. Use onStopTrackingTouch for expensive work. Material's Slider and RangeSlider (with valueFrom, valueTo, stepSize) accept floats and are preferred today. In Compose use Slider.

RatingBar

RatingBar shows and edits star ratings: numStars, stepSize (such as 0.5) and rating. Set style="?android:attr/ratingBarStyleSmall" for an indicator in a list, and isIndicator = true for display only. Compose has no built-in stars, so apps draw them with Row and Icon(Icons.Filled.Star) or use a library.

ProgressBar

ProgressBar has two modes. Indeterminate (a spinner or a moving bar) says "something is happening". Determinate (style="@style/Widget.AppCompat.ProgressBar.Horizontal", max, progress) shows a known percentage. Material adds CircularProgressIndicator and LinearProgressIndicator, with setProgressCompat(value, animated = true). Compose uses the same names: CircularProgressIndicator and LinearProgressIndicator.

ImageView

ImageView shows a drawable, bitmap or vector. scaleType (centerCrop, fitCenter, centerInside) controls how it fits, and contentDescription is essential for accessibility (set importantForAccessibility="no" for decorative images). Load network images with Coil or Glide, not by decoding bitmaps yourself; see Image Loading with Coil. In Compose this is Image or AsyncImage.

Kotlin
// read-only example
binding.avatar.load(user.avatarUrl) {   // Coil's ImageView extension
    placeholder(R.drawable.avatar_placeholder)
    crossfade(true)
}

The widgets' values often need converting for display: a slider 0 to 100 becomes a volume, a RatingBar 0 to 5 becomes a label, and a progress count becomes a percentage. The second stand-in models those mappings in plain functions that you can test without a device, which is also the good habit: keep the mapping out of the widget callback.

Kotlin Mapping widget values to UI text (stand-in)

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.

Views and Compose at a glance

Classic widgets, Compose names

TextView / EditText Text, TextField
Button / CheckBox Button, Checkbox, Switch
SeekBar / RatingBar Slider, custom stars
ProgressBar ProgressIndicator

Views keep their state inside; Compose keeps it in your code.

1 / 2

Common mistakes

  • Updating a widget from a listener it triggers. Setting isChecked in code fires the listener again; guard against loops (the stand-in above only fires on a real change).
  • Reading the text too early. editText.text is mutable and may be null-like; convert with text.toString().trim().
  • Forgetting contentDescription on meaningful images and icon buttons.
  • Hard-coded strings and colors in XML. Use resources so localization and dark mode work.
  • Doing heavy work in onProgressChanged. It fires for every pixel of the drag; use onStopTrackingTouch.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does the state of a classic EditText live?

    Classic widgets own their state; you read it (text, isChecked, progress) and push changes with setters. In Compose, you own the state and the widget displays it.
  2. 2. Which widget lets the user pick exactly one option out of several?

    RadioButtons inside a RadioGroup are mutually exclusive. CheckBoxes are independent.
  3. 3. What is the purpose of TextInputLayout?

    TextInputLayout is a Material Components wrapper that provides the label, error, helper text and icons for the field inside.
  4. 4. In SeekBar.onProgressChanged, what does the fromUser parameter tell you?

    fromUser is true for touch-driven changes and false when code calls setProgress, so you can avoid feedback loops.
  5. 5. Which Compose component replaces the classic Spinner?

    A drop-down choice in Compose uses ExposedDropdownMenuBox (Material 3) with a menu of items and your own selected-value state.

Summary

  • Widgets are Views you declare in XML, find with ViewBinding and observe with listeners; they hold their own state.
  • TextView shows text (use sp and string resources); EditText with TextInputLayout gives labels, errors and keyboards by inputType.
  • Spinner, CheckBox, RadioGroup, Switch, SeekBar, RatingBar and ProgressBar each report changes through their own listener.
  • ImageView needs a contentDescription and an image-loading library for network images.
  • Compose equivalents: Text, TextField, Button, Checkbox, RadioButton, Switch, Slider, ProgressIndicator, ExposedDropdownMenuBox, Image.
  • Keep mapping and validation in plain functions so you can test them without a device.

Next: Menus, Toolbars and Dialogs in XML