Android UI, Activities & Navigation

Common Views & Widgets

18 min Lesson 2 of 12

Common Views & Widgets

Every visible element on an Android screen is a subclass of android.view.View. Android ships dozens of ready-made View subclasses — called widgets — that cover the vast majority of UI needs. In this lesson you will work closely with the four most fundamental ones: TextView, Button, EditText, and ImageView. You will learn how each one is declared in XML, how it is wired up in Java, and the key attributes and API calls that every Android developer reaches for daily.

Declaring Views in XML vs Instantiating in Java

Android strongly encourages declaring the UI in XML layout files (inside res/layout/) and then referencing those views in Java via findViewById(). This separation keeps design concerns out of business logic and lets layout editors and accessibility tools introspect the UI independently of the running code.

Every XML view element must provide android:layout_width and android:layout_height. The two most common values are wrap_content (size to the content) and match_parent (fill the available space).

TextView — Displaying Text

TextView is the most-used widget in Android. It renders a string of text and supports rich formatting, clickable links, compound drawables, and HTML-tagged spans.

<!-- res/layout/activity_main.xml --> <TextView android:id="@+id/tvGreeting" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, World!" android:textSize="20sp" android:textColor="#212121" android:fontFamily="sans-serif-medium" android:layout_margin="16dp" />

Key attributes: android:text sets the static label (prefer string resources: @string/greeting). android:textSize must use sp units so it respects the user's system font-size preference. android:textColor accepts hex colours or colour resources.

In Java, you obtain a reference and manipulate it at runtime:

// MainActivity.java import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private TextView tvGreeting; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvGreeting = findViewById(R.id.tvGreeting); tvGreeting.setText("Welcome back, Edrees!"); // Make text selectable (useful for emails, phone numbers) tvGreeting.setTextIsSelectable(true); } }
Always use sp for text sizes, dp for everything else. sp (scale-independent pixels) scales with the user's accessibility font settings. Hard-coding px or dp for text will make your app inaccessible to users who need larger type.

Button — Handling Taps

Button extends TextView, so every text attribute applies. Its primary job is to fire an action when the user taps it. The preferred way to listen for taps is to attach an OnClickListener in code — do not use the deprecated android:onClick XML attribute in new projects.

<!-- res/layout/activity_main.xml --> <Button android:id="@+id/btnSave" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save" android:backgroundTint="@color/colorPrimary" android:textColor="@android:color/white" android:paddingHorizontal="24dp" />
// MainActivity.java import android.view.View; import android.widget.Button; import android.widget.Toast; Button btnSave = findViewById(R.id.btnSave); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Saved!", Toast.LENGTH_SHORT).show(); } });

The lambda form is more concise once you are comfortable with anonymous classes:

btnSave.setOnClickListener(v -> Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show() );
Disable the button while async work runs. Call btnSave.setEnabled(false) before starting a network or database operation and btnSave.setEnabled(true) when it completes. This prevents duplicate submissions — one of the most common bugs in Android forms.

EditText — Accepting User Input

EditText is a TextView with editing enabled. It is the primary way users type into your app. The android:inputType attribute is critical: it tells the soft keyboard what kind of input to present and enables automatic validation hints.

<!-- res/layout/activity_main.xml --> <EditText android:id="@+id/etEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter your email" android:inputType="textEmailAddress" android:maxLines="1" android:imeOptions="actionDone" android:layout_margin="16dp" />

Common inputType values: text, textPassword, textEmailAddress, phone, number, numberDecimal, textMultiLine. Each changes the keyboard layout shown to the user.

// MainActivity.java import android.widget.EditText; EditText etEmail = findViewById(R.id.etEmail); // Read the current value — always trim whitespace String email = etEmail.getText().toString().trim(); if (email.isEmpty()) { etEmail.setError("Email is required"); etEmail.requestFocus(); return; }

Use setError() to show an inline validation message directly below the field — Android draws a red icon and a popup tooltip automatically. Pair it with requestFocus() to scroll the user to the problem field.

Never read EditText content inside onResume() or a timer. Only read it when the user triggers an action (button tap, IME action). Reading it continuously defeats the purpose of user-initiated input and wastes CPU.

ImageView — Displaying Images

ImageView renders a drawable resource, a bitmap loaded at runtime, or a remote image (via a library like Glide or Picasso). The two most important attributes are android:src (the image source) and android:scaleType (how the image is scaled/cropped inside the view bounds).

<!-- res/layout/activity_main.xml --> <ImageView android:id="@+id/ivAvatar" android:layout_width="80dp" android:layout_height="80dp" android:src="@drawable/ic_avatar_placeholder" android:scaleType="centerCrop" android:contentDescription="User avatar" android:layout_margin="16dp" />

Common scaleType values:

  • centerCrop — scale uniformly until both dimensions fill the view; crop the excess. Best for profile pictures.
  • fitCenter — scale uniformly until the whole image fits inside the view with letterboxing. Good for logos and icons.
  • centerInside — like fitCenter but never enlarges an image smaller than the view.
  • fitXY — stretch to fill exactly, ignoring aspect ratio. Almost always looks wrong.

Changing the image at runtime:

// MainActivity.java import android.widget.ImageView; ImageView ivAvatar = findViewById(R.id.ivAvatar); // From a drawable resource ivAvatar.setImageResource(R.drawable.ic_user_photo); // From a Bitmap (e.g. decoded from a file or a camera result) // Bitmap bmp = BitmapFactory.decodeFile(path); // ivAvatar.setImageBitmap(bmp);
Always set android:contentDescription on every ImageView. Screen readers (TalkBack) announce this string to visually impaired users. If the image is purely decorative, set it to an empty string ("") so TalkBack skips it. Omitting it generates a lint warning and fails accessibility audits.

Wiring Everything Together — A Realistic Example

Here is a compact registration form that demonstrates all four widgets working together:

// RegistrationActivity.java public class RegistrationActivity extends AppCompatActivity { private EditText etName, etEmail; private Button btnRegister; private ImageView ivLogo; private TextView tvStatus; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); etName = findViewById(R.id.etName); etEmail = findViewById(R.id.etEmail); btnRegister = findViewById(R.id.btnRegister); ivLogo = findViewById(R.id.ivLogo); tvStatus = findViewById(R.id.tvStatus); ivLogo.setImageResource(R.drawable.ic_app_logo); btnRegister.setOnClickListener(v -> { String name = etName.getText().toString().trim(); String email = etEmail.getText().toString().trim(); if (name.isEmpty()) { etName.setError("Name is required"); etName.requestFocus(); return; } if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { etEmail.setError("Valid email is required"); etEmail.requestFocus(); return; } btnRegister.setEnabled(false); tvStatus.setText("Registering " + name + "..."); // ... perform registration, then re-enable button }); } }

Summary

TextView displays text; control its size with sp and its style with the many text attributes. Button fires an OnClickListener — attach it in Java, not in XML. EditText collects typed input; always specify inputType and validate with setError(). ImageView renders images; pick the right scaleType and always supply a contentDescription. In the next lesson you will handle user interaction events in depth.