0% found this document useful (0 votes)
3 views12 pages

Unit 3

The document discusses two design approaches in Android development: Procedural Design and Declarative Design, highlighting their characteristics and examples. It also covers practical implementations for a Sudoku app, including creating an opening screen, using alternate resources, implementing an About box, applying themes, adding menus and settings, and debugging techniques. Each section provides code snippets and explanations to guide developers in building and maintaining their applications effectively.

Uploaded by

echaithra28
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)
3 views12 pages

Unit 3

The document discusses two design approaches in Android development: Procedural Design and Declarative Design, highlighting their characteristics and examples. It also covers practical implementations for a Sudoku app, including creating an opening screen, using alternate resources, implementing an About box, applying themes, adding menus and settings, and debugging techniques. Each section provides code snippets and explanations to guide developers in building and maintaining their applications effectively.

Uploaded by

echaithra28
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/ 12

UNIT 3

DESIGNING BY DECLARATION:
1. Procedural Design (Imperative Programming)
Used in:
• Traditional Android View system (XML + Java/Kotlin)
Example:
val textView = TextView(this)
textView.text = "Hello, World!"
textView.textSize = 20f
linearLayout.addView(textView)
Characteristics:
• You manually manage UI components.
• Explicit state handling (findViewById, setText, etc.).
• Tedious updates when state changes.

2. Declarative Design
Used in:
• Jetpack Compose (Android)
Example using Jetpack Compose:
@Composable
fun Greeting(name: String) {
Text(text = "Hello, $name!")
}

Characteristics:
• UI is a function of state.
• System handles UI re-rendering.
• No findViewById or manual UI manipulation.
• Code is more concise and reactive.

DESIGNING A SIMPLE SUDUKO OPENING SCREEN:


MainActivity.kt:
package com.example.suduko

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


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

findViewById<Button>(R.id.btnNewGame).setOnClickListener {
// TODO: Start new game activity
}

findViewById<Button>(R.id.btnContinue).setOnClickListener {
// TODO: Continue previous game
}

findViewById<Button>(R.id.btnSettings).setOnClickListener {
// TODO: Open settings screen
}
}
}

activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="24dp">

<TextView
android:id="@+id/titleText"
android:text="Sudoku"
android:textSize="32sp"
android:textStyle="bold"
android:layout_marginBottom="32dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:id="@+id/btnNewGame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Game" />

<Button
android:id="@+id/btnContinue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Continue"
android:layout_marginTop="16dp" />
<Button
android:id="@+id/btnSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Settings"
android:layout_marginTop="16dp" />
</LinearLayout>

USING ALTERNATE RESOURCES:


In Android development with Kotlin, alternate resources refer to providing different versions of
resources (like layouts, strings, images, etc.) for different device configurations—such as screen size,
orientation, language, or API level.
Here's how to use alternate resources effectively in a Kotlin-based mobile app:

1. Use Resource Qualifiers


Create different resource folders with qualifiers:
• res/layout/ → default layout
• res/layout-land/ → for landscape orientation
• res/values/ → default values
• res/drawable-mdpi/ → for medium-density screens
• res/drawable-xhdpi/ → for extra high-density screens
For example, to support different languages:
res/values/strings.xml -> default (English)
res/values-es/strings.xml -> Spanish
res/values-fr/strings.xml -> French

2. Access Resources in Kotlin


Kotlin code doesn't need to change for different resources. Android automatically selects the correct
resource based on the device configuration.
val welcomeText = getString(R.string.welcome_message)

3. Use Configuration Programmatically


If needed, you can dynamically detect configuration and act accordingly:
val orientation = resources.configuration.orientation
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
// Do something specific to landscape
}
4. Load Specific Resources Programmatically (if needed)
You can manually load alternate resources (not recommended unless necessary):
val config = Configuration(resources.configuration)
config.setLocale(Locale("fr"))
val localizedContext = createConfigurationContext(config)
val frenchString = localizedContext.getString(R.string.welcome_message)

IMPLEMENTIMG ABOUT BOX:


1. Simple Approach: Using a Dialog
A quick way to implement an "About" box is via an AlertDialog.
fun showAboutDialog(context: Context) {
val appVersion = context.packageManager
.getPackageInfo(context.packageName, 0).versionName

AlertDialog.Builder(context)
.setTitle("About This App")
.setMessage("Version: $appVersion\n\nDeveloped by Your Name\nVisit:
https://yourwebsite.com")
.setPositiveButton("OK", null)
.show()
}
Call it in your activity or fragment like:
aboutButton.setOnClickListener {
showAboutDialog(this)
}

2. Using a Custom Layout


If you want more control (images, styling, etc.):
a) Create a layout: res/layout/dialog_about.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="20dp"
android:layout_width="match_parent" android:layout_height="wrap_content">
<ImageView
android:src="@drawable/ic_launcher"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_gravity="center"/>

<TextView
android:id="@+id/about_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="About this app"
android:paddingTop="10dp"
android:textAlignment="center"/>
</LinearLayout>
b) Load it in Kotlin:
fun showCustomAboutDialog(context: Context) {
val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_about, null)

val appVersion = context.packageManager


.getPackageInfo(context.packageName, 0).versionName

dialogView.findViewById<TextView>(R.id.about_text).text =
"Version: $appVersion\nDeveloped by Your Name"

AlertDialog.Builder(context)
.setView(dialogView)
.setPositiveButton("OK", null)
.show()
}

APPLYING A THEME:
Applying a theme in Android is a powerful way to maintain consistency and customize the
look and feel of your app. Below is a clear explanation of its importance, how to apply a
custom theme, and the difference between styles and themes.

Importance and Benefits of Applying a Theme


1. Consistent UI Design

Themes ensure all UI components (buttons, text, background, etc.) follow a uniform
appearance across activities and fragments.

2. Easy Maintenance

You can change your app’s entire look (e.g., from light to dark mode) by updating the theme
in one place instead of modifying each component individually.

3. Brand Identity

Themes help reinforce your app's branding (colors, fonts, logo styles) and improve user
recognition.

4. Reusability

Themes and styles make your UI scalable—apply them across multiple activities or views
with minimal duplication.

Applying a Custom Theme


Step 1: Define the Theme in res/values/themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<style name="Theme.SudokuApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Customize your theme -->
<item name="colorPrimary">#6200EE</item>
<item name="colorPrimaryVariant">#3700B3</item>
<item name="colorOnPrimary">#FFFFFF</item>
<item name="colorSecondary">#03DAC5</item>
<item name="android:textColor">#000000</item>
</style>
</resources>

You can also define separate values for themes in themes.xml (night) for dark mode.

Step 2: Apply the Theme in AndroidManifest.xml


<application
android:name=".MyApplication"
android:theme="@style/Theme.SudokuApp">
...
</application>

Difference Between Styles and Themes


Feature Style Theme
Applies to individual views
Scope Applies to the entire app or activity
(TextView, Button)
Inherits from theme classes (e.g.,
Inheritance Based on parent style
Material)
Example Use Styling a button’s text color or Defining overall color palette and font
Case padding family
android:theme="@style/MyTheme" in
How to Apply android:style="@style/MyStyle" in XML
manifest or activity
Toolbar, window background, system
Controls Text size, padding, background, etc.
bar colors, etc.

Example: Style vs Theme


Style (for a Button)

<style name="MyButtonStyle">
<item name="android:background">#6200EE</item>
<item name="android:textColor">#FFFFFF</item>
</style>

Usage:

<Button
style="@style/MyButtonStyle"
android:text="Click Me" />

Theme (for whole app)


<style name="Theme.MyApp" parent="Theme.Material3.DayNight">
<item name="colorPrimary">#FF5722</item>
</style>

Applied in AndroidManifest.xml as:

<application android:theme="@style/Theme.MyApp">
ADDING A MENU:

In any mobile app, menus provide an intuitive way to access actions and settings without
cluttering the main interface. For the Sudoku app, adding a menu enhances user experience
by offering easy access to important features such as starting a new game, viewing the
app’s settings, or accessing help and about information. By incorporating a menu into the
action bar (toolbar) or a floating action button (FAB), the user can quickly perform tasks
without navigating away from the main screen.

In this case, for the Sudoku app, the menu can include items like New Game, Settings, Help,
and Exit. The New Game item allows the user to start a fresh Sudoku puzzle, while the
Settings item can open a screen for configuring game difficulty or preferences. The Help
item can provide instructions or tips on how to play Sudoku, and the Exit item allows the
user to quit the game. This provides an efficient way to manage app functionality in a clean
and organized manner, all while keeping the main gameplay area uncluttered and user-
friendly.

By using a Toolbar to hold the menu and enabling features like icons and custom themes, the
menu becomes a seamless part of the overall app design, ensuring a polished and intuitive
user interface for all levels of users.

ADDING SETTINGS:

Steps to Add a Settings Screen in Your Sudoku App


1. Create a SettingsActivity

This activity will host your settings fragment.

package com.example.sudokuapp

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class SettingsActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager.beginTransaction()
.replace(android.R.id.content, SettingsFragment())
.commit()
}
}

2. Create a SettingsFragment

This fragment will define the settings options.


package com.example.sudokuapp

import android.os.Bundle
import androidx.preference.PreferenceFragmentCompat

class SettingsFragment : PreferenceFragmentCompat() {


override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
}
}

3. Define Preferences in XML

Create a preferences.xml file in res/xml/ to list the settings options.

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<ListPreference
android:key="difficulty"
android:title="Select Difficulty"
android:summary="%s"
android:defaultValue="medium"
android:entries="@array/difficulty_levels"
android:entryValues="@array/difficulty_values" />

<SwitchPreferenceCompat
android:key="sound"
android:title="Enable Sound"
android:defaultValue="true" />

</PreferenceScreen>

4. Add Difficulty Levels

In res/values/strings.xml, define the difficulty levels.

<string-array name="difficulty_levels">
<item>Easy</item>
<item>Medium</item>
<item>Hard</item>
</string-array>

<string-array name="difficulty_values">
<item>easy</item>
<item>medium</item>
<item>hard</item>
</string-array>

5. Add Settings Menu Item

In your main menu XML (res/menu/menu_main.xml), add a settings item.

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

6. Handle Menu Item Click

In your MainActivity, handle the click event for the settings menu item.

override fun onOptionsItemSelected(item: MenuItem): Boolean {


return when (item.itemId) {
R.id.menu_settings -> {
startActivity(Intent(this, SettingsActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
}

7. Declare SettingsActivity in Manifest

In your AndroidManifest.xml, declare the new activity.

<activity android:name=".SettingsActivity" />

DEBUGGING:

Debugging

Debugging is the process of identifying, analyzing, and resolving bugs or errors in


software to ensure the program runs correctly.

Importance of Debugging

• Ensures software correctness and reliability


• Helps prevent crashes or incorrect output
• Identifies logical, runtime, or syntax errors
• Saves development time in the long term
• Enhances understanding of code behavior.

Debugging with Log Messages


What It Is:

Logging involves placing statements in your code to print messages to the console (Logcat
in Android). These messages help track the flow of execution and inspect variable values at
runtime.
Why Use It:

• Quick insights into what your code is doing at specific moments.


• Ideal for simple issues like checking if a function is called, or if certain conditions are
met.

We use Log methods from Android's android.util.Log class.

Log.d("MainActivity", "Button clicked")


Log.i("Login", "User logged in successfully")
Log.e("Database", "Data fetch failed")
Log.wtf("GameEngine", "Unreachable code executed!")
Log.v("MainActivity", "onCreate: Initializing variables")

• Log.d() → Debug messages


• Log.i() → Info messages
• Log.w() → Warning messages
• Log.e() → Error messages

• Deep internal tracing


• Log.v() • Verbose
• Unexpected, critical errors
• Log.wtf() • Assert/Fatal

These logs appear in Logcat in Android Studio.

Drawbacks:

• Overuse can make Logcat cluttered, especially if not filtered.


• Log statements must be manually removed or disabled before releasing the app.
• Doesn’t allow real-time inspection of variables or logic flow.

Debugging with Debugger


What It Is:

The debugger is an advanced tool integrated into IDEs like Android Studio, which allows
developers to:

• Pause execution
• Inspect app state
• Watch variables
• Trace execution path without modifying code

Core Features:
1. Breakpoints:
Pause execution at specific lines.

val total = a + b // Add a breakpoint here to pause

2. Step Over (F8):


Execute the current line and pause at the next line.
3. Step Into (F7):
Go into method/function calls to debug inside them.
4. Evaluate Expression:
Check or change variable values in the paused state.
5. Call Stack Inspection:
See the series of function calls leading to the current line.
6. Watch Window:
Keep an eye on specific variables.

Benefits:

• Great for complex logic, null pointer exceptions, or unexpected behavior.


• Helps in understanding exactly where and why your code fails.
• Allows real-time variable inspection and manipulation.

Drawbacks:

• Takes time to learn for beginners.


• Requires setup (setting breakpoints, managing debug session).
• Slower than just running the app and logging messages.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy