0% found this document useful (0 votes)
7 views31 pages

Android Practical

The document provides a step-by-step guide for creating Android applications using Android Studio, covering installation, configuration, and project creation. It includes practical exercises such as creating a 'Hello World' app, implementing an activity lifecycle demo, building a simple calculator, and managing multiple activities. Each practical section details the necessary XML layout and Java code modifications required to achieve the desired functionality.

Uploaded by

pasito2857
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)
7 views31 pages

Android Practical

The document provides a step-by-step guide for creating Android applications using Android Studio, covering installation, configuration, and project creation. It includes practical exercises such as creating a 'Hello World' app, implementing an activity lifecycle demo, building a simple calculator, and managing multiple activities. Each practical section details the necessary XML layout and Java code modifications required to achieve the desired functionality.

Uploaded by

pasito2857
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/ 31

Android Practical

Practical : 1
Step 1: Download and Install Android Studio
1. Download Android Studio

👉 https://developer.android.com/studio
●​ Go to the official Android Studio website:​

●​ Click Download Android Studio and accept the terms.


●​ Choose the appropriate version for your OS (Windows, macOS, Linux).

2. Install Android Studio

●​ Run the installer and follow the setup instructions:


o​ Click Next → Choose components (Android SDK, Emulator) → Click Next
o​ Select the installation location → Click Next
o​ Click Install and wait for the installation to complete.
o​ Click Finish to launch Android Studio.

Step 2: Configure Android Studio


1. First-Time Setup

●​ When Android Studio opens, it will ask for setup preferences. Select:
o​ Standard Installation (Recommended for beginners).
o​ Click Finish to download additional SDK components.

2. Verify SDK Installation

●​ Open Android Studio → Click More Actions → SDK Manager.


●​ Ensure that the latest Android SDK version is installed.


●​ Check that the following essential components are installed:​

✅ Android SDK Platform​

✅ Android Virtual Device (AVD)​


SDK Tools (for Gradle builds, emulator, debugging)

Step 3: Create Your First Android Project

1.​ Open Android Studio → Click New Project.


2.​ Select Empty Activity → Click Next.
3.​ Configure the project:
o​ Project Name: HelloWorld
o​ Package Name: com.example.helloworld
o​ Language: Java (or Kotlin)
o​ Minimum API Level: API 21 (Android 5.0 Lollipop)
o​ Click Finish to create the project.

Step 4: Run Your First Android App


1. Using an Emulator

●​ Go to Tools → AVD Manager → Click Create Virtual Device.


●​ Select a device model (e.g., Pixel 4).
●​ Choose a System Image (e.g., Android 12) → Click Next.
●​ Click Finish to create the virtual device.
●​ ▶
Click Run ( ) to launch the emulator and test your app.

2. Using a Real Device

●​ Connect your Android phone via USB Cable.


●​ Enable Developer Mode:
o​ Go to Settings → About Phone → Tap Build Number 7 times.
●​ Enable USB Debugging:
o​ Go to Settings → Developer Options → Enable USB Debugging.

●​ Run the app on the real device using Run ( ) in Android Studio.

Step 5: Verify Everything is Working

●​ Open MainActivity.java and check for onCreate() method.


●​ Locate res/layout/activity_main.xml and confirm the TextView displaying "Hello World".
●​ Run the app and ensure it launches successfully on the emulator or real device.

Practical : 2

Step 1: Create a New Android Project

1.​ Open Android Studio.


2.​ Click on "New Project" → Select "Empty Activity" → Click Next.
3.​ Enter the following details:
o​ Name: HelloWorldApp
o​ Package Name: com.example.helloworld
o​ Save Location: Choose your preferred location
o​ Language: Java (or Kotlin, based on preference)
o​ Minimum API Level: API 21 (Android 5.0 Lollipop) or later
4.​ Click Finish and wait for the project to load.

Step 2: Modify activity_main.xml

1.​ Open res/layout/activity_main.xml.


2.​ Replace the existing code with the following:

<?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:gravity="center"
android:orientation="vertical"
android:background="#FFFFFF">

<TextView
android:id="@+id/tv_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:textSize="24sp"
android:textColor="#FF0000" />
</LinearLayout>

Explanation:

●​ Used LinearLayout with gravity="center" to position the text in the center.


●​ TextView displays "Hello World" with:
o​ textSize="24sp" (Font size)
o​ textColor="#FF0000" (Red color)

Step 3: Modify MainActivity.java (Optional, if needed)

1.​ Open java/com/example/helloworld/MainActivity.java.


2.​ Ensure the following code exists:

package com.example.helloworld;

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

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Explanation:

●​ onCreate() method sets the XML layout file (activity_main.xml) as the UI.

Step 4: Run the Application

1.​ Click Run (▶) in Android Studio.


2.​ Choose an Emulator or a Real Device.
3.​ The app will launch and display "Hello World" in red color in the center of the screen.

Expected Output:

A white screen with "Hello World" displayed in red color at the center.

Practical : 3
Step 1: Create a New Android Project

1.​ Open Android Studio.


2.​ Click "New Project" → Select "Empty Activity" → Click Next.
3.​ Enter the following details:
o​ Name: ActivityLifecycleDemo
o​ Package Name: com.example.activitylifecycle
o​ Save Location: Choose your preferred location
o​ Language: Java (or Kotlin)
o​ Minimum API Level: API 21 (Android 5.0 Lollipop) or later
4.​ Click Finish and wait for the project to load.

Step 2: Modify activity_main.xml

1.​ Open res/layout/activity_main.xml.


2.​ Replace the existing code with the following:

<?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:gravity="center"
android:orientation="vertical"
android:padding="20dp"
android:background="#F5F5F5">

<TextView
android:id="@+id/tv_lifecycle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity Lifecycle Demo"
android:textSize="20sp"
android:textColor="#000000"
android:textStyle="bold"/>
</LinearLayout>
Explanation:

●​ Used LinearLayout with gravity="center" to position the text.


●​ TextView displays "Activity Lifecycle Demo" as a heading.

Step 3: Modify MainActivity.java

1.​ Open java/com/example/activitylifecycle/MainActivity.java.


2.​ Replace the existing code with the following:

package com.example.activitylifecycle;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "ActivityLifecycle";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate() called");
Toast.makeText(this, "onCreate()", Toast.LENGTH_SHORT).show();
}

@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
Toast.makeText(this, "onStart()", Toast.LENGTH_SHORT).show();
}

@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
Toast.makeText(this, "onResume()", Toast.LENGTH_SHORT).show();
}

@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
Toast.makeText(this, "onPause()", Toast.LENGTH_SHORT).show();
}

@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
Toast.makeText(this, "onStop()", Toast.LENGTH_SHORT).show();
}

@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart() called");
Toast.makeText(this, "onRestart()", Toast.LENGTH_SHORT).show();
}

@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
Toast.makeText(this, "onDestroy()", Toast.LENGTH_SHORT).show();
}
}
Explanation:

●​ Log.d(TAG, "methodName() called"); → Logs lifecycle events to Logcat.


●​ Toast.makeText(this, "methodName()", Toast.LENGTH_SHORT).show(); → Displays Toast messages
when lifecycle methods are triggered.

Expected Output:
1.​ When the app starts:

o​ Toasts: onCreate(), onStart(), onResume().


o​ Logcat:

D/ActivityLifecycle: onCreate() called


D/ActivityLifecycle: onStart() called
D/ActivityLifecycle: onResume() called
2.​ When pressing the home button:
o​ Toasts: onPause(), onStop().
o​ Logcat:

D/ActivityLifecycle: onPause() called


D/ActivityLifecycle: onStop() called
3.​ When reopening the app:

o​ Toasts: onRestart(), onStart(), onResume().


o​ Logcat:

D/ActivityLifecycle: onRestart() called


D/ActivityLifecycle: onStart() called
D/ActivityLifecycle: onResume() called
4.​ When pressing the back button to exit:

o​ Toasts: onPause(), onStop(), onDestroy().


o​ Logcat:

D/ActivityLifecycle: onPause() called


D/ActivityLifecycle: onStop() called
D/ActivityLifecycle: onDestroy() called

Practical : 4
Step 1: Modify activity_main.xml (User Interface)

1.​ Open res/layout/activity_main.xml.


2.​ Replace the existing code with the following:

<?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:padding="20dp"
android:gravity="center"
android:background="#F5F5F5">

<EditText
android:id="@+id/et_num1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter First Number"
android:inputType="numberDecimal"
android:padding="10dp"/>

<EditText
android:id="@+id/et_num2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Second Number"
android:inputType="numberDecimal"
android:padding="10dp"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:paddingTop="10dp">

<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:padding="10dp"
android:layout_margin="5dp"/>

<Button
android:id="@+id/btn_subtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:padding="10dp"
android:layout_margin="5dp"/>

<Button
android:id="@+id/btn_multiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="×"
android:padding="10dp"
android:layout_margin="5dp"/>

<Button
android:id="@+id/btn_divide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="÷"
android:padding="10dp"
android:layout_margin="5dp"/>
</LinearLayout>

<TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result: "
android:textSize="20sp"
android:textStyle="bold"
android:paddingTop="20dp"
android:gravity="center"/>
</LinearLayout>
Explanation:

●​ Two EditText fields for number input.


●​ Four Buttons for arithmetic operations (+, -, ×, ÷).
●​ TextView to display the result.
●​ LinearLayout for button arrangement.

Step 2: Modify MainActivity.java (Logic for Calculator)

1.​ Open java/com/example/calculator/MainActivity.java.


2.​ Replace the existing code with the following:

package com.example.calculator;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText etNum1, etNum2;


private TextView tvResult;
private Button btnAdd, btnSubtract, btnMultiply, btnDivide;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize UI elements
etNum1 = findViewById(R.id.et_num1);
etNum2 = findViewById(R.id.et_num2);
tvResult = findViewById(R.id.tv_result);
btnAdd = findViewById(R.id.btn_add);
btnSubtract = findViewById(R.id.btn_subtract);
btnMultiply = findViewById(R.id.btn_multiply);
btnDivide = findViewById(R.id.btn_divide);

// Set button click listeners


btnAdd.setOnClickListener(view -> performOperation("+"));
btnSubtract.setOnClickListener(view -> performOperation("-"));
btnMultiply.setOnClickListener(view -> performOperation("*"));
btnDivide.setOnClickListener(view -> performOperation("/"));
}

private void performOperation(String operator) {


String num1Str = etNum1.getText().toString();
String num2Str = etNum2.getText().toString();

if (num1Str.isEmpty() || num2Str.isEmpty()) {
Toast.makeText(this, "Please enter both numbers", Toast.LENGTH_SHORT).show();
return;
}

double num1 = Double.parseDouble(num1Str);


double num2 = Double.parseDouble(num2Str);
double result = 0;

switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
Toast.makeText(this, "Cannot divide by zero", Toast.LENGTH_SHORT).show();
return;
}
result = num1 / num2;
break;
}

tvResult.setText("Result: " + result);


}
}
Explanation:

●​ Retrieves input values from EditText.


●​ Handles button clicks using setOnClickListener().
●​ Performs arithmetic operations using performOperation() method.
●​ Displays results in TextView.
●​ Handles division by zero to prevent errors.

Practical : 5

Step 1: Modify AndroidManifest.xml

1.​ Open AndroidManifest.xml.


2.​ Add the second activity inside the <application> tag.

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


Step 2: Create UI for Main Activity (activity_main.xml)

1.​ Open res/layout/activity_main.xml.


2.​ Replace the existing code with the following:

<?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:padding="20dp"
android:gravity="center"
android:background="#F5F5F5">

<Button
android:id="@+id/btn_explicit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second Activity"
android:padding="10dp"
android:layout_marginBottom="10dp"/>

<Button
android:id="@+id/btn_implicit_web"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Website"
android:padding="10dp"
android:layout_marginBottom="10dp"/>

<Button
android:id="@+id/btn_implicit_call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Make a Call"
android:padding="10dp"
android:layout_marginBottom="10dp"/>

<Button
android:id="@+id/btn_implicit_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send an Email"
android:padding="10dp"/>
</LinearLayout>

Step 3: Implement MainActivity (MainActivity.java)

1.​ Open java/com/example/intentdemo/MainActivity.java.


2.​ Replace the existing code with the following:
package com.example.intentdemo;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private Button btnExplicit, btnWeb, btnCall, btnEmail;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize buttons
btnExplicit = findViewById(R.id.btn_explicit);
btnWeb = findViewById(R.id.btn_implicit_web);
btnCall = findViewById(R.id.btn_implicit_call);
btnEmail = findViewById(R.id.btn_implicit_email);

// Explicit Intent - Navigate to SecondActivity


btnExplicit.setOnClickListener(view -> {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
});

// Implicit Intent - Open a Web Page


btnWeb.setOnClickListener(view -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
startActivity(intent);
});

// Implicit Intent - Make a Call


btnCall.setOnClickListener(view -> {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+1234567890"));
startActivity(intent);
});

// Implicit Intent - Send an Email


btnEmail.setOnClickListener(view -> {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:[email protected]"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Hello from Android");
intent.putExtra(Intent.EXTRA_TEXT, "This is a test email.");
startActivity(intent);
});
}
}
Explanation:
●​ Explicit Intent → Navigates from MainActivity to SecondActivity.
●​ Implicit Intent:
o​ Opens a website (Intent.ACTION_VIEW with URL).
o​ Opens dialer with a phone number (Intent.ACTION_DIAL).
o​ Opens email app with a pre-filled email (Intent.ACTION_SENDTO).

Step 4: Create the Second Activity

1.​ Right-click on com.example.intentdemo → New → Activity → Empty Activity.


2.​ Name it SecondActivity → Click Finish.

Step 5: Modify activity_second.xml (Second Activity UI)

1.​ Open res/layout/activity_second.xml.


2.​ Replace the existing code with the following:

<?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="20dp"
android:background="#E3F2FD">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Second Activity"
android:textSize="20sp"
android:textColor="#000000"
android:textStyle="bold"/>
</LinearLayout>

Step 6: Modify SecondActivity.java

1.​ Open java/com/example/intentdemo/SecondActivity.java.


2.​ Replace the existing code with the following:

package com.example.intentdemo;

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

public class SecondActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}

Practical : 6
Step 1: Modify AndroidManifest.xml
Make sure the MainActivity is correctly registered as the launcher activity.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Implementation Using Linear Layout


Step 2: Modify activity_main.xml for Linear Layout

1.​ Open res/layout/activity_main.xml.


2.​ Replace the existing code with the following:

<?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:padding="20dp"
android:gravity="center"
android:background="#F5F5F5">

<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Username"
android:padding="10dp"/>

<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Password"
android:inputType="textPassword"
android:padding="10dp"/>
<CheckBox
android:id="@+id/chk_remember"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remember Me"/>

<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:padding="10dp"
android:layout_marginTop="10dp"/>
</LinearLayout>

Step 3: Implement MainActivity.java (Login Logic)

1.​ Open java/com/example/logindemo/MainActivity.java.


2.​ Replace the existing code with the following:

package com.example.logindemo;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText etUsername, etPassword;


private CheckBox chkRemember;
private Button btnLogin;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize UI elements
etUsername = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_password);
chkRemember = findViewById(R.id.chk_remember);
btnLogin = findViewById(R.id.btn_login);

// Set button click listener


btnLogin.setOnClickListener(view -> {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if (username.isEmpty() || password.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter username and password",
Toast.LENGTH_SHORT).show();
} else {
String message = chkRemember.isChecked() ? "Login successful with Remember Me checked!" : "Login
successful!";
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
}
}

Implementation Using Relative Layout


Step 4: Modify activity_relative.xml for Relative Layout

1.​ Open res/layout/ → New Layout Resource File → Name it activity_relative.xml.


2.​ Replace the existing code with the following:

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
android:background="#E3F2FD">

<EditText
android:id="@+id/et_username_rel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Username"
android:padding="10dp"
android:layout_marginBottom="10dp"/>

<EditText
android:id="@+id/et_password_rel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Password"
android:inputType="textPassword"
android:padding="10dp"
android:layout_below="@id/et_username_rel"/>

<CheckBox
android:id="@+id/chk_remember_rel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remember Me"
android:layout_below="@id/et_password_rel"
android:layout_marginTop="10dp"/>
<Button
android:id="@+id/btn_login_rel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:padding="10dp"
android:layout_below="@id/chk_remember_rel"
android:layout_marginTop="10dp"/>
</RelativeLayout>

Implementation Using Table Layout


Step 5: Modify activity_table.xml for Table Layout

1.​ Open res/layout/ → New Layout Resource File → Name it activity_table.xml.


2.​ Replace the existing code with the following:

<?xml version="1.0" encoding="utf-8"?>


<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
android:background="#FFF3E0">

<TableRow>
<EditText
android:id="@+id/et_username_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Username"
android:padding="10dp"/>
</TableRow>

<TableRow>
<EditText
android:id="@+id/et_password_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Password"
android:inputType="textPassword"
android:padding="10dp"/>
</TableRow>

<TableRow>
<CheckBox
android:id="@+id/chk_remember_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remember Me"/>
</TableRow>
<TableRow>
<Button
android:id="@+id/btn_login_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:padding="10dp"/>
</TableRow>
</TableLayout>

Practical : 7
Step 1: Modify activity_main.xml (UI Design)

1.​ Open res/layout/activity_main.xml.


2.​ Replace the existing code with the following:

<?xml version="1.0" encoding="utf-8"?>


<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
android:background="#F5F5F5">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">

<!-- Full Name -->


<EditText
android:id="@+id/et_fullname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Full Name"
android:padding="10dp"/>

<!-- Email -->


<EditText
android:id="@+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"
android:inputType="textEmailAddress"
android:padding="10dp"/>

<!-- Password -->


<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:padding="10dp"/>

<!-- Gender -->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender"
android:textSize="16sp"
android:textStyle="bold"
android:layout_marginTop="10dp"/>

<RadioGroup
android:id="@+id/rg_gender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<RadioButton
android:id="@+id/rb_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"/>

<RadioButton
android:id="@+id/rb_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"/>

</RadioGroup>

<!-- Country Selection -->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Country"
android:textSize="16sp"
android:textStyle="bold"
android:layout_marginTop="10dp"/>

<Spinner
android:id="@+id/spinner_country"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"/>

<!-- Terms & Conditions -->


<CheckBox
android:id="@+id/chk_terms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I agree to the terms & conditions"/>

<!-- Submit Button -->


<Button
android:id="@+id/btn_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register"
android:padding="10dp"
android:layout_marginTop="20dp"/>
</LinearLayout>
</ScrollView>

Step 2: Implement MainActivity.java (Form Logic)

1.​ Open java/com/example/registrationform/MainActivity.java.


2.​ Replace the existing code with the following:

package com.example.registrationform;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText etFullName, etEmail, etPassword;


private RadioGroup rgGender;
private Spinner spinnerCountry;
private CheckBox chkTerms;
private Button btnRegister;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize UI elements
etFullName = findViewById(R.id.et_fullname);
etEmail = findViewById(R.id.et_email);
etPassword = findViewById(R.id.et_password);
rgGender = findViewById(R.id.rg_gender);
spinnerCountry = findViewById(R.id.spinner_country);
chkTerms = findViewById(R.id.chk_terms);
btnRegister = findViewById(R.id.btn_register);

// Populate Spinner with country list


String[] countries = {"Select Country", "USA", "India", "UK", "Canada", "Australia"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item,
countries);
spinnerCountry.setAdapter(adapter);

// Set button click listener


btnRegister.setOnClickListener(view -> registerUser());
}

private void registerUser() {


String fullName = etFullName.getText().toString().trim();
String email = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
int selectedGenderId = rgGender.getCheckedRadioButtonId();
String gender = selectedGenderId == R.id.rb_male ? "Male" : "Female";
String country = spinnerCountry.getSelectedItem().toString();
boolean isTermsAccepted = chkTerms.isChecked();

// Validation
if (fullName.isEmpty() || email.isEmpty() || password.isEmpty() || selectedGenderId == -1 || "Select
Country".equals(country)) {
Toast.makeText(this, "Please fill all fields correctly!", Toast.LENGTH_SHORT).show();
} else if (!isTermsAccepted) {
Toast.makeText(this, "You must accept the terms & conditions!", Toast.LENGTH_SHORT).show();
} else {
String message = "Registration Successful!\nName: " + fullName + "\nEmail: " + email + "\nGender: " +
gender + "\nCountry: " + country;
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
}

Practical : 8
Step 1: Modify activity_main.xml (GridLayout UI Design)

1.​ Open res/layout/activity_main.xml.


2.​ Replace the existing code with the following:

<?xml version="1.0" encoding="utf-8"?>


<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="3"
android:rowCount="3"
android:padding="20dp"
android:background="#F5F5F5">

<!-- Row 1 -->


<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Name:"
android:textSize="18sp"
android:textStyle="bold"
android:layout_columnSpan="1"
android:gravity="center_vertical"/>

<EditText
android:id="@+id/et_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:layout_columnSpan="2"
android:padding="10dp"/>

<!-- Row 2 -->


<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Email:"
android:textSize="18sp"
android:textStyle="bold"
android:layout_columnSpan="1"
android:gravity="center_vertical"/>

<EditText
android:id="@+id/et_email"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Enter Email"
android:inputType="textEmailAddress"
android:layout_columnSpan="2"
android:padding="10dp"/>

<!-- Row 3 -->


<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Password:"
android:textSize="18sp"
android:textStyle="bold"
android:layout_columnSpan="1"
android:gravity="center_vertical"/>

<EditText
android:id="@+id/et_password"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Enter Password"
android:inputType="textPassword"
android:layout_columnSpan="2"
android:padding="10dp"/>

<!-- Row 4 -->


<Button
android:id="@+id/btn_submit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="16sp"
android:layout_columnSpan="3"
android:padding="10dp"/>
</GridLayout>
Explanation:

●​ GridLayout is used as the root layout with rowCount="3" and columnCount="3".


●​ UI elements are arranged in a 3-column format.
●​ layout_columnSpan="2" makes elements span across multiple columns.
●​ gravity="center_vertical" aligns TextView elements properly.

Step 2: Implement MainActivity.java (Handling Button Clicks)

1.​ Open java/com/example/gridlayoutdemo/MainActivity.java.


2.​ Replace the existing code with the following:

package com.example.gridlayoutdemo;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText etName, etEmail, etPassword;


private Button btnSubmit;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize UI elements
etName = findViewById(R.id.et_name);
etEmail = findViewById(R.id.et_email);
etPassword = findViewById(R.id.et_password);
btnSubmit = findViewById(R.id.btn_submit);

// Set button click listener


btnSubmit.setOnClickListener(view -> submitForm());
}

private void submitForm() {


String name = etName.getText().toString().trim();
String email = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
// Validation
if (name.isEmpty() || email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please fill all fields!", Toast.LENGTH_SHORT).show();
} else {
String message = "Submitted Successfully!\nName: " + name + "\nEmail: " + email;
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
}

Practical : 9

Step 1: Implementing Options Menu


Modify res/menu/menu_main.xml

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


2.​ Right-click on the menu folder → New → Menu Resource File → Name it menu_main.xml.
3.​ Add the following code:

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_home"
android:title="Home"/>
<item
android:id="@+id/menu_settings"
android:title="Settings"/>
<item
android:id="@+id/menu_about"
android:title="About"/>
</menu>
Modify MainActivity.java to Handle Menu Clicks

1.​ Open java/com/example/menunavigationdemo/MainActivity.java.


2.​ Modify the file as follows:

package com.example.menunavigationdemo;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_home:
Toast.makeText(this, "Home Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.menu_about:
startActivity(new Intent(this, AboutActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Create Additional Activities (Settings and About)

1.​ Right-click on java/com.example.menunavigationdemo → New → Activity → Empty Activity.


2.​ Name it SettingsActivity and repeat for AboutActivity.
3.​ Replace their Java files with:

SettingsActivity.java

package com.example.menunavigationdemo;

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

public class SettingsActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
}
AboutActivity.java

package com.example.menunavigationdemo;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class AboutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
}

Step 2: Implementing Navigation Drawer

1.​ Right-click res/layout/ → New → Layout Resource File → Name it activity_main.xml.


2.​ Replace the code with:

<?xml version="1.0" encoding="utf-8"?>


<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

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

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to Menu Navigation"
android:textSize="18sp"
android:gravity="center"
android:padding="20dp"/>
</LinearLayout>

<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/menu_navigation"/>
</androidx.drawerlayout.widget.DrawerLayout>
Modify res/menu/menu_navigation.xml

1.​ Right-click on the menu folder → New → Menu Resource File → Name it menu_navigation.xml.
2.​ Replace the content with:

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/nav_home"
android:title="Home"/>
<item
android:id="@+id/nav_settings"
android:title="Settings"/>
<item
android:id="@+id/nav_about"
android:title="About"/>
</menu>
Modify MainActivity.java to Handle Navigation Drawer
Modify the file as follows:
package com.example.menunavigationdemo;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;

public class MainActivity extends AppCompatActivity {

private DrawerLayout drawerLayout;


private ActionBarDrawerToggle toggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

drawerLayout = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

NavigationView navigationView = findViewById(R.id.nav_view);


navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
{
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
Toast.makeText(MainActivity.this, "Home Selected", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_settings:
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
break;
case R.id.nav_about:
startActivity(new Intent(MainActivity.this, AboutActivity.class));
break;
}
return true;
}
});
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Practical : 10
Step 1: Modify activity_main.xml (Fragment Container & Buttons)

1.​ Open res/layout/activity_main.xml.


2.​ Replace the content with the following:

<?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:padding="20dp">

<Button
android:id="@+id/btn_fragment1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Fragment 1" />

<Button
android:id="@+id/btn_fragment2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Fragment 2" />

<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#DDDDDD"/>
</LinearLayout>
Explanation:

●​ A FrameLayout (fragment_container) is used as a placeholder for fragments.


●​ Two Buttons allow switching between fragments dynamically.
Step 2: Create Fragment Layouts

1.​ Right-click on res/layout/ → New → Layout Resource File → Name it fragment_one.xml.


2.​ Add the following code:

<?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:background="#FFC107"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Fragment 1"
android:textSize="20sp"
android:textColor="#000000"/>
</LinearLayout>

3.​ Repeat the process and create fragment_two.xml:

<?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:background="#03A9F4"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Fragment 2"
android:textSize="20sp"
android:textColor="#FFFFFF"/>
</LinearLayout>
Explanation:

●​ Fragment 1 (Yellow) displays a message in black.


●​ Fragment 2 (Blue) displays a message in white.

Step 3: Create Fragment Java Classes


Create FragmentOne.java

1.​ Right-click java/com.example.fragmentdemo → New → Java Class → Name it FragmentOne.java.


2.​ Add the following code:

package com.example.fragmentdemo;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class FragmentOne extends Fragment {


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
Create FragmentTwo.java

1.​ Right-click java/com.example.fragmentdemo → New → Java Class → Name it FragmentTwo.java.


2.​ Add the following code:

package com.example.fragmentdemo;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class FragmentTwo extends Fragment {


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
Explanation:

●​ Both fragments extend the Fragment class and load their respective layouts inside onCreateView().

Step 4: Modify MainActivity.java to Handle Fragment Switching

1.​ Open java/com/example/fragmentdemo/MainActivity.java.


2.​ Replace the code with:

package com.example.fragmentdemo;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

private Button btnFragment1, btnFragment2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnFragment1 = findViewById(R.id.btn_fragment1);
btnFragment2 = findViewById(R.id.btn_fragment2);

// Load Fragment 1 by default


loadFragment(new FragmentOne());

btnFragment1.setOnClickListener(view -> loadFragment(new FragmentOne()));


btnFragment2.setOnClickListener(view -> loadFragment(new FragmentTwo()));
}

private void loadFragment(Fragment fragment) {


FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}

You might also like