0% found this document useful (0 votes)
21 views33 pages

Android WebView and UI Components Guide

The document provides an overview of various Android components, including WebView for displaying web pages, ImageSwitcher for animating images, SMS messaging, email sending via intents, Google Maps integration, BroadcastReceiver for listening to events, Handler for managing tasks, TableLayout for structured data display, and ScrollView for scrolling content. Each component includes use cases, best practices, and step-by-step implementation guidance. The document serves as a comprehensive guide for developers looking to utilize these features in their Android applications.

Uploaded by

Nehal
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)
21 views33 pages

Android WebView and UI Components Guide

The document provides an overview of various Android components, including WebView for displaying web pages, ImageSwitcher for animating images, SMS messaging, email sending via intents, Google Maps integration, BroadcastReceiver for listening to events, Handler for managing tasks, TableLayout for structured data display, and ScrollView for scrolling content. Each component includes use cases, best practices, and step-by-step implementation guidance. The document serves as a comprehensive guide for developers looking to utilize these features in their Android applications.

Uploaded by

Nehal
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

WebView

A WebView in Android is a view component ([Link]) that allows you to


display web pages inside your Android app — just like a mini-browser embedded in your
app.

🔍 In Simple Terms:
WebView = Browser inside your app UI

🧱 Use Cases:
 Show your website or help pages inside the app.
 Display embedded dashboards, maps, or widgets.
 Render dynamic HTML content.
 Integrate hybrid apps (mix of web and native features).

✅ Step-by-step WebView Example


1. Add Internet Permission

In [Link]:

2. Add WebView to Layout

Create a layout file: res/layout/activity_main.xml


3. Activity Java Code

Create or edit [Link]:


⚠️ Best Practices
 Security: Avoid loading untrusted websites or enabling addJavascriptInterface()
without safeguards.
 Downloads: For file downloads, implement DownloadListener.
 Cookies: Use CookieManager for session support if needed.
 Permissions: Handle runtime permissions for file access if required by the site.
📷 What is ImageSwitcher in Android?

ImageSwitcher is a specialized ViewSwitcher in Android that allows you to animate


between images. It is commonly used when you want to transition between images with
smooth animations, such as fade, slide, or zoom.

✅ Key Features of ImageSwitcher:

 Shows one image at a time.


 Allows smooth transitions between images (e.g., fade-in/out).
 Requires a ViewFactory to define how the images should be displayed (typically an
ImageView).
 Efficient for memory since it reuses two views and switches between them.

📦 Use Cases:

 Image galleries or sliders.


 Step-by-step walkthroughs or tutorials.
 Banner advertisements.
 Any UI element requiring animated image changes.

⚙️ How It Works:

1. You provide a ViewFactory that returns a new ImageView.


2. You set an image with setImageResource() or setImageDrawable().
3. You can assign inAnimation and outAnimation to control how images change.
🔧 Step 1: Add Images
Place these images in res/drawable/:

 [Link]
 [Link]
 [Link]
(You can use JPG or WebP as well — just be sure the names match.)

🧱 Step 2: activity_main.xml
🧱 Step 3: [Link]
📱 SMS Messaging in Android – Explained Simply

SMS (Short Message Service) is the standard way to send text messages between mobile
devices. In Android, your app can either:

✅ 1. Send SMS Silently (Programmatically)

This means the app sends the SMS without user interaction.

🔧 Requirements:

 Permission: You must declare SEND_SMS permission in [Link].


 Runtime Permission: Android 6.0+ requires you to request permission at runtime.
 SIM Card: The device must have a working SIM card.
 APIs Used: SmsManager

🔁 Flow:

1. App checks if it has SEND_SMS permission.


2. If not, request it.
3. If granted, get phone number & message.
4. Use [Link]().sendTextMessage(...).

🧱 Example:
✅ 2. Kotlin Code: Send SMS with Runtime Permission Handling
✅ 3. XML Layout (res/layout/activity_main.xml):
🔎 Notes:

 Works only on real device with SIM card.


 Test with actual phone numbers.
 If it still doesn't work:
o Ensure SMS plan is active.
o Try sending to another phone number.
o Use Logcat to catch any errors in delivery.
✅ 3. Open Default SMS App with a Message Pre-filled

This doesn't need special permissions because it uses an intent to open the user's messaging
app.

✅ Example:
📧 Sending Email in Android – Full Example with Explanation

Android does not send email directly like it does SMS (via SmsManager). Instead, it opens
the user’s preferred email client (like Gmail, Outlook, etc.) using an intent. Your app can
pre-fill recipient, subject, and body — then the user sends it.

✅ Why Use Intent for Email?

 Avoids handling email protocols (SMTP, IMAP, etc.).


 No need for login or server config.
 Secure — the user controls sending.

✅ Step-by-Step: Sending an Email in Android

1. No Permission Required!

Sending email via intent needs no special permission.

2. UI (XML Layout)
4. Activity Code in Kotlin
🧱 Key Notes

 Intent.ACTION_SENDTO: Ensures only email apps are opened.


 EXTRA_EMAIL, EXTRA_SUBJECT, EXTRA_TEXT: Pre-fill details.
 You don’t handle sending — the email app does it.
 If you want to send attachments, you need ACTION_SEND and
setType("message/rfc822").
Google Map

✅ Prerequisites

1. Use a Google APIs Emulator Image


o When creating the emulator, choose a system image like:
 Google APIs x86_64 or x86 (not just AOSP or plain Android)
o Without this, Google Play Services (which maps depend on) won't be
available.
2. Enable Internet Access
o The emulator must have internet access (it does by default).
o Maps require network calls to load tiles, geocode, etc.

🌐 Step 1: Sign Up for a Google Maps API Key


1. Go to the Google Cloud Console:
👉 [Link]
2. Sign in with your Google account.
3. Create a new project (or select an existing one):
o Click the project dropdown (top-left next to Google Cloud logo).
o Click "New Project".
o Give it a name, then click "Create".

📍 Step 2: Enable the Maps SDK for Android


1. After selecting your project, go to the API Library:
👉 [Link]
2. Search for "Maps SDK for Android".
3. Click it, then click "Enable".
🔑 Step 3: Create an API Key
1. Go to APIs & Services > Credentials:
👉 [Link]
2. Click "Create Credentials" → "API key".
3. A new API key will be generated. Copy it.
4. Restrict your API key (recommended):
o Click "Edit API key".
o Under Application restrictions, choose Android apps.
o Add your app's package name and SHA-1 certificate fingerprint.
 Example:
 Package name: [Link]
 SHA-1: Use ./gradlew signingReport or Android Studio’s
Gradle tab to get it.
5. Under API restrictions, choose:
o ✅ Restrict key
o ✅ Select only Maps SDK for Android
6. Click Save.

📌 Final Step: Add API Key to Your App


In your [Link]:
✅ Step 4: [Link]
Create [Link] in your src/main/java/... folder:
🚀 Run It!
Once your emulator is running a Google Play or Google APIs image
(not AOSP-only), you should see a map with a marker.

🚀 Result
 When the app launches, it requests location permission.
 On grant, it gets your current location and shows it on the map with a marker.

❗ Note:
 This example uses last known location. For real-time tracking, you'd use
LocationRequest with updates.
 Works on emulators only with GPS enabled and location set.
🧱 Notes

 Zoom controls appear in the bottom right corner of the map.


 These are in addition to pinch-to-zoom, which is always available.
 uiSettings gives you control over map gestures, buttons, compass, etc.

✅ What Is a BroadcastReceiver?
A BroadcastReceiver in Android listens for system-wide or app-specific broadcast
messages (intents).
You can use it to react to:

 System events (e.g., battery low, airplane mode)


 Custom events in your app (e.g., user logout, sync complete)

Use Case Example: Custom Broadcast


✅ What is a Handler?
A Handler in Android allows you to:

 Post tasks (Runnables) to be executed on a specific thread (usually the main/UI


thread).
 Schedule messages or delayed tasks.
 Communicate between threads (e.g., background thread updating UI thread).

It works with a Looper, which runs a message loop on a thread.

💡 Common Use Cases


 Updating UI from a background thread.
 Delaying execution (postDelayed).
 Scheduling repeated tasks.
 Handling messages in a thread.

📱 Example: Using Handler to Delay a Toast Message


🧱 Explanation
 Handler([Link]()): Binds the handler to the main thread's
message queue.
 postDelayed(Runnable, delayMillis): Schedules a task to run after a delay.
 Useful when you want to delay UI updates or animations.
⚠️ Modern Alternatives
 Since API 30, consider using:
o Handler([Link]()).post { ... }
o CoroutineScope([Link]).launch { delay(3000); ... } ←
Recommended

📘 What is TableLayout in Android?


TableLayout is a ViewGroup in Android that arranges its child views into rows and columns,
similar to an HTML table. Each row is defined by a TableRow object, and each cell within a
row can contain any type of View, such as TextView, ImageView, or even another
TableLayout. This layout is particularly useful for displaying structured data like forms,
invoices, or contact [Link]+5Android Developers+5OSChina Tool+5Android
Developers+2OSChina Tool+2Android Developers+2

Key Features:

 Rows and Columns: Each TableRow represents a single row, and each child within a
TableRow represents a cell. The number of columns is determined by the row with the
most cells. Android Developers
 No Built-in Borders: By default, TableLayout does not display borders for rows,
columns, or cells. Borders must be manually added using background drawables or
other methods. Demo2s+3Android Developers+3Android Developers+3Android
Developers
 Dynamic Data: You can populate a TableLayout programmatically with dynamic
data, making it suitable for displaying lists that may change over time.

🔧 Enhancing TableLayout with Borders and Dynamic Data


To display a TableLayout with visible borders and dynamic content, follow these steps:

1. Define a Cell Border Drawable

Create a drawable resource to define the border style for each cell.
📱 Step 3: Populate the Table Layout Dynamically
In your Activity, populate the TableLayout with dynamic data.

[Link]:
✅ Final Notes
 Borders: The android:divider and android:showDividers attributes in the
TableLayout XML define the borders between rows and columns. The cell_border
drawable applied to each TextView defines the individual cell borders.
 Dynamic Data: The for loops in the MainActivity populate the table dynamically
based on the data array. You can replace this with data from a database or other
sources as needed.
 Customization: You can customize the appearance of the table by modifying the
cell_border drawable, adjusting padding, text size, and other attributes of the
TextView.

By following these steps, you can create a visually structured table in Android with dynamic
data and visible borders.

✅ What is ScrollView?
ScrollView is a vertical scroll container in Android. It allows users to scroll content that
is larger than the screen size. It can contain only one direct child, usually a LinearLayout
or other layout with multiple views.

📁 Example Layout File (activity_main.xml)


🔁 Note on Nesting
 You cannot place multiple views directly inside a ScrollView.
 Always wrap them in a layout like LinearLayout or Other Layout.

You might also like