0% found this document useful (0 votes)
28 views23 pages

Unit 2 Part A

The document outlines the compilation process of XML layout files in Android, detailing how XML layouts are processed, converted into binary format, and referenced in Java/Kotlin code through R.java. It describes the structure and behavior of Views and ViewGroups, including event handling and rendering processes, as well as various layout types like LinearLayout, RelativeLayout, and ConstraintLayout. Additionally, it covers best practices for adapting to screen orientations and managing UI components dynamically during runtime.

Uploaded by

mythris107
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views23 pages

Unit 2 Part A

The document outlines the compilation process of XML layout files in Android, detailing how XML layouts are processed, converted into binary format, and referenced in Java/Kotlin code through R.java. It describes the structure and behavior of Views and ViewGroups, including event handling and rendering processes, as well as various layout types like LinearLayout, RelativeLayout, and ConstraintLayout. Additionally, it covers best practices for adapting to screen orientations and managing UI components dynamically during runtime.

Uploaded by

mythris107
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT 2 (PART A)

Working with user interface using views.

Compilation process of XML layout files in android:


1. XML Layout File Processing (Build Time)
When you define a UI layout in an XML file (e.g., activity_main.xml in res/layout), it
undergoes several steps before being used in an Android app.
• The AAPT (Android Asset Packaging Tool) processes all XML resource files.
• It converts XML files (like layouts, drawables, and styles) into a binary format that
is optimized for fast access.
• The processed resources are stored in the APK.
Generation of R.java
• AAPT generates the R.java file, which acts as a reference to resources.
• The layout XML file is assigned an ID in R.layout:
• These IDs are used in Java/Kotlin code to reference layouts.
Compiling UI Elements
• The XML files are compiled into a binary format and packaged into the APK.
• They are not converted directly into Java classes but remain as optimized binary
XML.
• During app execution, Android reads these binary XML files and inflates them into
Java objects.

2. Compilation into Android GUI Classes


• Unlike Java/Kotlin code, XML layouts are not compiled into Java classes.
• Instead, Android provides APIs (like LayoutInflater) to parse the binary XML files at
runtime and create corresponding View objects dynamically.
• Example:
setContentView(R.layout.activity_main)
o This method locates the corresponding XML resource using
R.layout.activity_main.
o It then loads and converts it into a tree of View objects.
3. Loading the UI in the onCreate() Method
The UI is loaded in the onCreate() method of an Activity:
setContentView(R.layout.activity_main)
• This method calls LayoutInflater.inflate(), which:
o Reads the binary XML layout file.
o Creates Java objects (View hierarchy).
o Attaches them to the activity’s Window.
View Binding
• Each widget (e.g., Button, TextView) in the XML is instantiated as a Java/Kotlin
object.
• You can reference these views using findViewById() or View Binding:
val myButton: Button = findViewById(R.id.button)
o Here, findViewById() fetches the reference from the inflated layout.

4. UI Creation at Runtime
When the app is running, the Android system dynamically creates and manages UI
components:
XML to View Object Conversion
• Android loads the binary XML layout and inflates it into a View hierarchy.
• Example hierarchy for activity_main.xml:
ConstraintLayout
├── TextView
├── Button
• Each widget (e.g., TextView, Button) is a Java/Kotlin object at runtime.
Rendering on Screen
• The Android View System takes the inflated View objects and draws them on the
screen using the Android Rendering Pipeline.
• The measure → layout → draw cycle ensures that views are properly displayed.

Main Components of a Screen in Android Studio


1. Views (UI Elements)
A View is the basic building block of the UI. It is a rectangular UI component that users
interact with.
Examples of Views:
• TextView → Displays text.
• EditText → Input field for user text.
• Button → Clickable button for actions.
• ImageView → Displays images.
• CheckBox → Selectable checkbox.
• RadioButton → One selection from multiple options.
• Switch → Toggle ON/OFF.
• ProgressBar → Indicates loading or progress.
• SeekBar → A slider for selecting a value.
Features of views:
a. Appearance & Behavior
• Appearance:
o Defined by attributes like background, textSize, padding, margin, visibility,
etc.
o Supports themes & styles for consistency.
o Can be modified dynamically via code.
• Behavior:
o Determines how the view responds to user actions.
o Can have scrolling, resizing, animations, etc.
o Uses View attributes like clickable, focusable, and enabled.

b. Hierarchy of Views
Views are structured in a hierarchical manner:
• ViewGroup: A container that holds multiple views (e.g., LinearLayout,
ConstraintLayout).
• Child Views: Individual UI elements inside a ViewGroup.
• The View hierarchy follows a tree structure, with the ViewGroup as the parent and
UI elements as children.

Example Hierarchy:
ConstraintLayout (Parent)
├── TextView (Child)
├── Button (Child)
├── ImageView (Child)

c. Event Handling
Views handle user interactions like taps, swipes, and key presses using:
• Listeners (setOnClickListener, setOnTouchListener, etc.).
• Gestures (e.g., swipe, long press via GestureDetector).
• Focus & Input events (keyboard, touch, drag).
Example: Click Event on a Button
button.setOnClickListener {
Toast.makeText(this, "Button Clicked!", Toast.LENGTH_SHORT).show()
}

d. Rendering of Views
Android follows a three-phase rendering process:
1. Measure: Calculates the size of each view.
2. Layout: Determines the position of each view.
3. Draw: Renders the UI on the screen.
Optimizing Rendering:
• Use View recycling (e.g., RecyclerView instead of multiple TextViews).
• Avoid nested layouts (prefer ConstraintLayout for complex UIs).
• Use hardware acceleration (android:hardwareAccelerated="true").

2. ViewGroups (Containers for Views)


A ViewGroup is a special type of View that contains other Views (child views). It organizes
multiple views on the screen.
Types of ViewGroups (Layouts):
• LinearLayout → Arranges views in a row or column.
• RelativeLayout → Positions views relative to each other.
• ConstraintLayout → Flexible layout with constraints (recommended).
• FrameLayout → Used for stacking views.
• ScrollView → Enables scrolling for long content.
• RecyclerView → Displays lists or grids efficiently.
Features of view groups:
• Container for Views: Holds and manages child views (Button, TextView, etc.).
• Layout Management: Determines how child views are arranged.
• View Hierarchy Control: Defines the relationship between parent and child views.
• Event Handling & Propagation: Manages how user events (touch, click) are passed
through the hierarchy.
• Optimized Rendering: Uses measure, layout, and draw phases to optimize UI
performance.

3. LAYOUTS
A Layout in Android is a ViewGroup that defines how child views (widgets like TextView,
Button, etc.) are arranged on the screen.

(a) LinearLayout

• Arranges views in a single row or column.


• Uses android:orientation="vertical" or "horizontal" to specify direction.
• Example:

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"/>

</LinearLayout>

• Best for: Simple, stacked UI elements.

(b) RelativeLayout Arranges views relative to each other or the parent.


• Uses layout_alignParent and layout_below attributes.
• Example:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:layout_centerHorizontal="true"/>

</RelativeLayout>

• Best for: Older projects (now replaced by ConstraintLayout).

(c) ConstraintLayout A flexible and powerful layout that allows positioning views using
constraints.

• Improves performance by reducing nested layouts.


• Example:

<androidx.constraintlayout.widget.ConstraintLayout

android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

• Best for: Complex, modern UI designs.

(d) FrameLayout

• Used to stack views on top of each other.


• Useful for fragments and overlapping views.
• Example:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/background_image"/>

</FrameLayout>

• Best for: Overlapping UI components, fragment containers.

(e) GridLayout

• Organizes UI elements into a grid of rows and columns.


• Similar to an HTML table.
• Example:

<GridLayout

android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="2">

<TextView
android:text="Item 1"
android:layout_column="0"/>

<TextView
android:text="Item 2"
android:layout_column="1"/>
</GridLayout>

• Best for: Grid-based UI, dashboards.

(f) TableLayout

• Uses rows and columns like an HTML table.


• Example:

<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TableRow>
<TextView android:text="Row 1, Column 1"/>
<TextView android:text="Row 1, Column 2"/>
</TableRow>

<TableRow>
<TextView android:text="Row 2, Column 1"/>
<TextView android:text="Row 2, Column 2"/>
</TableRow>
</TableLayout>

Features of layouts:
Structure – Defines how child views are arranged within a ViewGroup.
✔ Positioning – Determines where views appear on the screen.
✔ Sizing – Controls width and height of elements.
✔ Orientation – Supports horizontal or vertical organization.
✔ Nesting – Allows embedding layouts inside each other.
✔ Flexibility – Adapts to different screen sizes and orientations.
✔ Alignment – Positions child views within the layout.
✔ Margin & Padding – Adds space between views (margin) and inside views (padding).
✔ Scalability – Ensures UI elements adjust to different devices and resolutions.
✔ Performance – Optimizes rendering for smooth UI performance.
✔ XML Representation – Layouts are defined in XML for clarity and separation from code.
✔ Dynamic Layout Creation – Layouts can be created and modified at runtime in
Kotlin/Java.

4. Widgets (Interactive UI Components)


Widgets are specialized UI components used for user interactions.
Common Widgets:
• ListView → Displays a list of items.
• RecyclerView → Advanced and optimized list.
• CardView → Displays information in a card format.
• ViewPager → Swipeable pages.
• BottomNavigationView → Navigation bar at the bottom.
• NavigationDrawer → Sidebar menu for navigation.
Adapting to screen orientation:
Adapting to screen orientation in Android ensures a smooth user experience when switching
between portrait and landscape modes. Android handles orientation changes by destroying
and recreating the activity, which can lead to data loss if not managed properly. To handle
this, developers can use different layout resources (res/layout for portrait and res/layout-
land for landscape) to provide optimized UI designs for each orientation. Alternatively, using
ConstraintLayout helps create responsive layouts that adjust dynamically. To preserve data
during rotation, developers can use ViewModel, onSaveInstanceState(), or configChanges
in the AndroidManifest.xml. Additionally, Jetpack Compose and Fragments offer a more
flexible way to handle UI across different screen orientations without unnecessary activity
recreation. Proper orientation handling improves usability and ensures consistency across
different devices.

Anchoring views:

1. Anchoring in LinearLayout (Stacking Views)


Uses sequential positioning (top-to-bottom or left-to-right).
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="start">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Left Anchored"/>
</LinearLayout>

Attribute Purpose

android:gravity - Aligns content inside LinearLayout

android:layout_gravity - Positions a child inside its parent


android:layout_margin - Adds spacing around the view

android:padding - Adds spacing inside the view

android:layout_weight - Distributes space among child views

android:layout_margin - Adds spacing around the view

Use gravity for aligning multiple views inside the LinearLayout.


Use layout_gravity when anchoring a single view in the layout.
Use layout_weight for dynamic spacing.

2. Anchoring in FrameLayout (Overlaying Views)


Uses android:layout_gravity for positioning.
Example: Centered Text
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Centered"
android:layout_gravity="center"/>
</FrameLayout>
Attribute Description

layout_gravity="center": Centers view inside parent

layout_gravity="bottom": Pins view to bottom of parent

layout_gravity="end": Pins view to right (end) of parent

3. Relative Layout:
<RelativeLayout
android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView
android:id="@+id/textTopLeft"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="Top Left"

android:layout_alignParentTop="true"

android:layout_alignParentStart="true"/>
</RelativeLayout>

Attribute Purpose

android:layout_alignParentTop Aligns the view to the top of the parent

android:layout_alignParentBottom Aligns the view to the bottom of the parent

android:layout_alignParentStart Aligns the view to the start (left in LTR) of the parent

android:layout_alignParentEnd Aligns the view to the end (right in LTR) of the parent
android:layout_centerHorizontal Centers the view horizontally

android:layout_centerVertical Centers the view vertically

android:layout_centerInParent Centers the view both horizontally and vertically

android:layout_above Positions a view above another view

android:layout_below Positions a view below another view

android:layout_toStartOf Positions a view to the start of another view

android:layout_toEndOf Positions a view to the end of another view

4. Constraint layout:

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Top left"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toStartOf="parent"/>
Attribute Purpose

Constraints
ConstraintLayout
(layout_constraintStart_toStartOf)

Aligning to parent/sibling
RelativeLayout
(layout_alignParentTop)

Stacking + Gravity (gravity,


LinearLayout
layout_weight)

Overlaying + Gravity
FrameLayout
(layout_gravity)

Resizing and repositioning views:

Resizing and repositioning views in Android ensures that UI elements adapt properly to

different screen sizes, resolutions, and orientations. Android provides several ways to achieve this:

Using ConstraintLayout
• Constraints: Use app:layout_constraint* attributes to position views relative to each

other or the parent container.

• Bias & Guidelines: Adjust view positions dynamically using horizontal/vertical bias
(layout_constraintHorizontal_bias).
• Example:

<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Click Me"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.3"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Creating separate layouts for different orientations:


Step 1: Create the Default Layout (Portrait)
• This file is placed in res/layout/ and is used when the device is in portrait mode.
File: res/layout/activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- Title Text -->


<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>

<!-- Button centered below the TextView -->


<Button
android:id="@+id/myButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Click Me"
app:layout_constraintTop_toBottomOf="@id/title"
capp:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="20dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>
Used in Portrait Mode

Step 2: Create a Separate Layout for Landscape Mode


• The landscape layout is placed in res/layout-land/
• The Button moves to the right of the TextView
File: res/layout-land/activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Title Text -->
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>

<!-- Button repositioned to the right of TextView -->


<Button
android:id="@+id/myButton"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Click Me"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="@id/title"
android:layout_marginStart="20dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Used in Landscape Mode

Step 3: How Android Chooses the Layout


When the device is rotated, Android automatically switches between the layouts:
• Portrait Mode: Uses res/layout/activity_main.xml
• Landscape Mode: Uses res/layout-land/activity_main.xml

When the orientation of an Android device changes, the activity is restarted by default.
This means
1. The current activity is destroyed (onDestroy())
2. A new instance of the activity is created (onCreate())
This process is done because the layout changes (e.g., switching between
res/layout/ and res/layout-land/).

Activity Lifecycle Changes During Orientation Change


When orientation changes, the following lifecycle callbacks occur:
1. onPause() – The current activity is paused.
2. onStop() – The activity is stopped.
3. onDestroy() – The current activity instance is destroyed.
4. onCreate() – A new activity instance is created.
5. onStart() – The new instance starts.
6. onResume() – The new instance resumes and is now active.

Persisting state information during changes in configuration:


1. onSaveInstanceState() (Best for Small Data)
Used to store small, temporary data (like strings, numbers, or boolean values).
Stores data in a Bundle, which is automatically restored after recreation.
Example: Saving and Restoring User Input
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("user_input", inputField.text.toString())
}
Benefits of onSaveInstanceState():
• Automatically restores data after screen rotation.
• Best for small amounts of data like text fields.
• Limitations: Not ideal for large objects like images, lists, or API responses.

2. Handling Configuration Changes Manually (Not Recommended)


You can prevent activity recreation using android:configChanges in AndroidManifest.xml:
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize" />

Then, override onConfigurationChanged():


override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// Handle UI changes manually
}

3. ViewModel (Best for UI-Related Data)

Recommended for storing UI-related data like user inputs, API results, and temporary state.
ViewModel survives configuration changes, so the data remains even after screen rotation.

Steps to Use ViewModel

1. Create a ViewModel class.


2. Store data inside ViewModel.
3. Use ViewModelProvider in Activity or Fragment.

Example: Storing User Input Using ViewModel

Create a ViewModel class:

class MainViewModel : ViewModel() {


var userInput: String = ""
}

Use ViewModel in Activity:

class MainActivity : AppCompatActivity() {

private val viewModel: MainViewModel by viewModels()

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val inputField = findViewById<EditText>(R.id.inputField)


val submitButton = findViewById<Button>(R.id.myButton)
val outputText = findViewById<TextView>(R.id.outputText)

// Restore data after rotation


inputField.setText(viewModel.userInput)

submitButton.setOnClickListener {
viewModel.userInput = inputField.text.toString()
outputText.text = "You entered: ${viewModel.userInput}"
}
}
}

Benefits of ViewModel:

• Retains data even after orientation changes.


• No need to manually save and restore data.
• Works well with LiveData for automatic UI updates.

Action bar:

The Action Bar is a UI component in Android that provides navigation, branding,

and user actions at the top of an app screen. It is an essential part of the AppCompatActivity

and enhances user interaction with menus, icons, and navigation elements.

Components of the Action Bar

The Action Bar consists of the following key components:

(a) App Icon / Logo (Optional)

• Displays the app icon or logo on the left side.


• Can be enabled using getSupportActionBar()?.setDisplayShowHomeEnabled(true).
• Example:

supportActionBar?.setLogo(R.drawable.ic_logo)
supportActionBar?.setDisplayUseLogoEnabled(true)

(b) Title & Subtitle

• The title represents the current activity.


• The subtitle provides additional context.
• Example:

supportActionBar?.title = "Home"
supportActionBar?.subtitle = "Welcome to the app"
(c) Navigation (Up Button & Back Button)

• Up Button: Navigates to the parent activity.


• Back Button: Uses the system back stack.
• Example:

supportActionBar?.setDisplayHomeAsUpEnabled(true)

(d) Action Items (Menu)

• Used for important actions like search, settings, and sharing.


• Can be added via menu XML (res/menu/menu_main.xml):

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_settings"
android:title="Settings"
android:icon="@drawable/ic_settings"
android:showAsAction="always"/>
</menu>

• Implement in MainActivity.kt:

override fun onCreateOptionsMenu(menu: Menu?): Boolean {


menuInflater.inflate(R.menu.menu_main, menu)
return true
}

(e) Overflow Menu

• Displays additional actions when screen space is limited.


• Items with android:showAsAction="never" appear in the overflow menu.

(f) Custom Views

• Allows adding a custom layout to the Action Bar.


• Example:

val customView = layoutInflater.inflate(R.layout.custom_action_bar, null)


supportActionBar?.customView = customView
supportActionBar?.setDisplayShowCustomEnabled(true)

Creating action bar:


Creating an Action Bar in Android involves using the built-in support from AppCompatActivity
or replacing it with a custom Toolbar. By default, the Action Bar provides navigation, branding,
and interactive actions. It can be customized by setting a title, subtitle, icons, and menu items.
To add actions, a menu resource file (res/menu/menu_main.xml) is created, which is then inflated
in onCreateOptionsMenu(). Additionally, replacing the Action Bar with a Toolbar allows greater
flexibility in design, enabling placement anywhere in the layout. This is done by defining a Toolbar
widget in XML and setting it as the ActionBar in the activity using setSupportActionBar(toolbar).
The Action Bar can also be hidden dynamically using supportActionBar?.hide(), or removed
permanently by using a NoActionBar theme in themes.xml.

Adding action items to the action bar:

1. Create a Menu Resource File

You'll need to create a menu XML file inside the res/menu/ directory.

Steps:

1. Right-click on res → New → Android Resource Directory.


2. Set Resource Type to menu.
3. Right-click on the newly created menu folder** → New → Menu resource file.
4. Name it menu_main.xml.

res/menu/menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_settings"
android:icon="@android:drawable/ic_menu_preferences"
android:title="Settings"
android:showAsAction="ifRoom"/>

<item
android:id="@+id/action_share"
android:icon="@android:drawable/ic_menu_share"
android:title="Share"
android:showAsAction="ifRoom"/>
</menu>

2. Inflate Menu in onCreateOptionsMenu


In your MainActivity.kt, override onCreateOptionsMenu to inflate the menu.

MainActivity.kt

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

// Inflate the menu


override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}

// Handle menu item clicks


override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> {
Toast.makeText(this, "Settings Clicked", Toast.LENGTH_SHORT).show()
true
}
R.id.action_share -> {
Toast.makeText(this, "Share Clicked", Toast.LENGTH_SHORT).show()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}

Creating User Interface Programatically:


In Android, UI can be created using XML layouts (recommended) or programmatically in Kotlin/Java.
Creating UI programmatically provides more flexibility when dynamic views are needed, such as adding
elements at runtime based on user input.

Key Components of Programmatic UI


1. View Creation: Use Button(this), TextView(this), etc., where this is the Context.
2. Layout Parameters: Define size using LayoutParams.
3. Event Handling: Set setOnClickListener for user interaction.
4. Adding Views: Use addView(view) to place elements inside a parent layout.
5. Setting as Content View: Use setContentView(layout) to display the UI.

import android.graphics.Color
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

// Create a LinearLayout
val layout = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setBackgroundColor(Color.LTGRAY)
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}

// Create a Button
val button = Button(this).apply {
text = "Click Me"
setBackgroundColor(Color.BLUE)
setTextColor(Color.WHITE)
setOnClickListener {
text = "Clicked!"
}
}
layout.addView(button)
setContentView(layout)
}
}

You might also like