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

Mad Final All

The document contains multiple Android application programs demonstrating various UI components and functionalities, including displaying student information, implementing auto-complete text views, toggle buttons, and basic math operations. Each section includes Java code for the main activity and corresponding XML layout files. The examples illustrate the use of different layouts such as LinearLayout, TableLayout, and FrameLayout.

Uploaded by

1234mayurk
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 views64 pages

Mad Final All

The document contains multiple Android application programs demonstrating various UI components and functionalities, including displaying student information, implementing auto-complete text views, toggle buttons, and basic math operations. Each section includes Java code for the main activity and corresponding XML layout files. The examples illustrate the use of different layouts such as LinearLayout, TableLayout, and FrameLayout.

Uploaded by

1234mayurk
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/ 64

Sorted Text Files from Zip Archive

1. 1write a program to display student name and marks.txt


Java Code (MainActivity.java):
java
Copy
Edit
package com.example.studentinfo;

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

public class MainActivity extends AppCompatActivity {


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

// Create TextViews dynamically to display the student's name and marks


TextView nameTextView = findViewById(R.id.nameTextView);
TextView marksTextView = findViewById(R.id.marksTextView);

// Set the student's name and marks


String studentName = "John Doe";
int studentMarks = 85;

nameTextView.setText("Student Name: " + studentName);


marksTextView.setText("Marks: " + studentMarks);
}
}
XML Code (activity_main.xml):
xml
Copy
Edit
<?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="16dp"
android:gravity="center">

<!-- TextView to display the student's name -->


<TextView
android:id="@+id/nameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Name: "
android:textSize="18sp"
android:layout_marginBottom="10dp" />

<!-- TextView to display the student's marks -->


<TextView
android:id="@+id/marksTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Marks: "
android:textSize="18sp" />

</LinearLayout>

2. 2write a program to display student name , year , college name using linear
layout.txt
activity_main.xml
xml
Copy 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:padding="20dp"
android:gravity="center"
android:background="#F5F5F5">

<TextView
android:id="@+id/studentName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Name: Mayur Khalse"
android:textSize="20sp"
android:textColor="#000000"
android:padding="10dp" />
<TextView
android:id="@+id/year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Year: Third Year"
android:textSize="20sp"
android:textColor="#000000"
android:padding="10dp" />

<TextView
android:id="@+id/collegeName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="College: Government Polytechnic Nashik"
android:textSize="20sp"
android:textColor="#000000"
android:padding="10dp" />

</LinearLayout>

3. 3write a program to display info about 10 students using tablelayout.txt


activity_main.xml
xml
Copy code
<?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="wrap_content"
android:padding="16dp"
android:stretchColumns="*"
android:background="#FFFFFF">

<!-- Header Row -->


<TableRow>
<TextView
android:text="Roll No"
android:textStyle="bold"
android:padding="8dp"
android:background="#DDDDDD"
android:textColor="#000000" />
<TextView
android:text="Name"
android:textStyle="bold"
android:padding="8dp"
android:background="#DDDDDD"
android:textColor="#000000" />

<TextView
android:text="Year"
android:textStyle="bold"
android:padding="8dp"
android:background="#DDDDDD"
android:textColor="#000000" />
</TableRow>

<!-- Student Rows -->


<TableRow>
<TextView android:text="1" android:padding="8dp" />
<TextView android:text="Mayur Khalse" android:padding="8dp" />
<TextView android:text="Third" android:padding="8dp" />
</TableRow>

<TableRow>
<TextView android:text="2" android:padding="8dp" />
<TextView android:text="Atharva Nirantar" android:padding="8dp" />
<TextView android:text="Third" android:padding="8dp" />
</TableRow>

<TableRow>
<TextView android:text="3" android:padding="8dp" />
<TextView android:text="Shubham Dawange" android:padding="8dp" />
<TextView android:text="Third" android:padding="8dp" />
</TableRow>

<TableRow>
<TextView android:text="4" android:padding="8dp" />
<TextView android:text="Pooja Sharma" android:padding="8dp" />
<TextView android:text="Third" android:padding="8dp" />
</TableRow>

<TableRow>
<TextView android:text="5" android:padding="8dp" />
<TextView android:text="Pushkar Rane" android:padding="8dp" />
<TextView android:text="Third" android:padding="8dp" />
</TableRow>

<TableRow>
<TextView android:text="6" android:padding="8dp" />
<TextView android:text="Sneha Patil" android:padding="8dp" />
<TextView android:text="Third" android:padding="8dp" />
</TableRow>

<TableRow>
<TextView android:text="7" android:padding="8dp" />
<TextView android:text="Rohan Joshi" android:padding="8dp" />
<TextView android:text="Third" android:padding="8dp" />
</TableRow>

<TableRow>
<TextView android:text="8" android:padding="8dp" />
<TextView android:text="Aarti Kale" android:padding="8dp" />
<TextView android:text="Third" android:padding="8dp" />
</TableRow>

<TableRow>
<TextView android:text="9" android:padding="8dp" />
<TextView android:text="Rahul Deshmukh" android:padding="8dp" />
<TextView android:text="Third" android:padding="8dp" />
</TableRow>

<TableRow>
<TextView android:text="10" android:padding="8dp" />
<TextView android:text="Neha Bhagat" android:padding="8dp" />
<TextView android:text="Third" android:padding="8dp" />
</TableRow>

</TableLayout>

4. 4write a program to implement the concept of frame layout (display text


over image.txt
activity_main.xml
xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- Background Image -->


<ImageView
android:id="@+id/backgroundImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/sample_image"
android:scaleType="centerCrop" />

<!-- Overlay Text -->


<TextView
android:id="@+id/overlayText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to My App"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:layout_gravity="center" />

</FrameLayout>

5. 5write a program to implement autocompletetextview which will show list of


cities when user will type.txt
activity_main.xml
xml
Copy 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:padding="20dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter City Name:"
android:textSize="18sp"
android:paddingBottom="10dp" />
<AutoCompleteTextView
android:id="@+id/autoCompleteCity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Start typing a city..."
android:textSize="16sp"
android:padding="10dp"
android:background="@android:drawable/editbox_background" />
</LinearLayout>
✅ MainActivity.java
java
Copy code
package com.example.autocompleteexample;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

String[] cities = {
"Mumbai", "Delhi", "Chennai", "Kolkata", "Bangalore",
"Hyderabad", "Pune", "Nashik", "Ahmedabad", "Nagpur"
};

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

AutoCompleteTextView autoCompleteCity = findViewById(R.id.autoCompleteCity);

ArrayAdapter<String> adapter = new ArrayAdapter<>(


this,
android.R.layout.simple_dropdown_item_1line,
cities
);

autoCompleteCity.setAdapter(adapter);
autoCompleteCity.setThreshold(1); // start suggesting after typing 1 character
}
}
6. 6write a program to implement concept of toggle button display status on
click of button.txt
activity_main.xml
xml
Copy 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:gravity="center"
android:padding="20dp">

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="ON"
android:textOff="OFF" />

<TextView
android:id="@+id/statusText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Status: OFF"
android:textSize="20sp"
android:paddingTop="20dp" />
</LinearLayout>
MainActivity.java
java
Copy code
package com.example.togglebuttonexample;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

toggleButton = findViewById(R.id.toggleButton);
statusText = findViewById(R.id.statusText);

toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (toggleButton.isChecked()) {
statusText.setText("Status: ON");
} else {
statusText.setText("Status: OFF");
}
}
});
}
}

7. 7write a program to perform basic math operation.txt


activity_main.xml
xml
Copy 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:padding="20dp"
android:gravity="center_horizontal">

<EditText
android:id="@+id/number1"
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/number2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Second Number"
android:inputType="numberDecimal"
android:padding="10dp"
android:layout_marginTop="10dp" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp"
android:gravity="center"
android:weightSum="4">

<Button
android:id="@+id/btnAdd"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="+" />

<Button
android:id="@+id/btnSub"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="-" />

<Button
android:id="@+id/btnMul"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="×" />

<Button
android:id="@+id/btnDiv"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="÷" />
</LinearLayout>

<TextView
android:id="@+id/resultText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result: "
android:textSize="20sp"
android:layout_marginTop="30dp" />
</LinearLayout>
✅ MainActivity.java
java
Copy code
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 androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

EditText number1, number2;


Button btnAdd, btnSub, btnMul, btnDiv;
TextView resultText;

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

number1 = findViewById(R.id.number1);
number2 = findViewById(R.id.number2);
btnAdd = findViewById(R.id.btnAdd);
btnSub = findViewById(R.id.btnSub);
btnMul = findViewById(R.id.btnMul);
btnDiv = findViewById(R.id.btnDiv);
resultText = findViewById(R.id.resultText);

btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double a = getInput(number1);
double b = getInput(number2);
resultText.setText("Result: " + (a + b));
}
});

btnSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double a = getInput(number1);
double b = getInput(number2);
resultText.setText("Result: " + (a - b));
}
});

btnMul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double a = getInput(number1);
double b = getInput(number2);
resultText.setText("Result: " + (a * b));
}
});

btnDiv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double a = getInput(number1);
double b = getInput(number2);
if (b != 0)
resultText.setText("Result: " + (a / b));
else
resultText.setText("Cannot divide by zero");
}
});
}

private double getInput(EditText field) {


String text = field.getText().toString();
if (text.isEmpty()) {
return 0;
} else {
return Double.parseDouble(text);
}
}
}

8. 8. write a program to implement concept of radio button for gender selection


display selected radioButton onClick of Button.txt
activity_main.xml
xml
Copy 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:padding="20dp"
android:gravity="center_horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Gender"
android:textSize="20sp"
android:layout_marginBottom="20dp" />

<RadioGroup
android:id="@+id/radioGroupGender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

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

<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
<RadioButton
android:id="@+id/radioOther"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Other" />
</RadioGroup>

<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_marginTop="20dp" />

<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Selected Gender: "
android:textSize="18sp"
android:layout_marginTop="20dp" />
</LinearLayout>
✅ MainActivity.java
java
Copy code
package com.example.radiobuttonexample;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

RadioGroup radioGroupGender;
Button btnSubmit;
TextView tvResult;

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

radioGroupGender = findViewById(R.id.radioGroupGender);
btnSubmit = findViewById(R.id.btnSubmit);
tvResult = findViewById(R.id.tvResult);

btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedId = radioGroupGender.getCheckedRadioButtonId();

if (selectedId != -1) {
RadioButton selectedRadio = findViewById(selectedId);
String gender = selectedRadio.getText().toString();
tvResult.setText("Selected Gender: " + gender);
} else {
tvResult.setText("Please select a gender.");
}
}
});
}
}

9. 9. write a program to display horizontal progressBar on click of Button make


a start button for it and the progress bar starts from 0 to 100 using thread.txt
activity_main.xml
xml
Copy 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:padding="20dp"
android:gravity="center_horizontal">

<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
android:layout_marginTop="50dp" />

<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:layout_marginTop="30dp" />
</LinearLayout>
✅ MainActivity.java
java
Copy code
package com.example.progressbarexample;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

ProgressBar progressBar;
Button btnStart;
int progressStatus = 0;
Handler handler = new Handler(); // To update UI from background thread

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

progressBar = findViewById(R.id.progressBar);
btnStart = findViewById(R.id.btnStart);

btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

progressStatus = 0;
progressBar.setProgress(0);

Thread thread = new Thread(new Runnable() {


@Override
public void run() {
while (progressStatus < 100) {
progressStatus++;
try {
Thread.sleep(50); // delay to show progress smoothly
} catch (InterruptedException e) {
e.printStackTrace();
}

handler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(progressStatus);
}
});
}
}
});
thread.start();
}
});
}
}

10. 10. write a program to implement listview which show list of various
subjects (MAD, WBP,PWP,ETI,MAN).txt
activity_main.xml
xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subjects:"
android:textSize="20sp"
android:layout_marginBottom="10dp"/>

<ListView
android:id="@+id/listViewSubjects"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
✅ MainActivity.java
java
Copy code
package com.example.listviewexample;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

ListView listViewSubjects;
String[] subjects = {"MAD", "WBP", "PWP", "ETI", "MAN"};

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

listViewSubjects = findViewById(R.id.listViewSubjects);

ArrayAdapter<String> adapter = new ArrayAdapter<>(


this,
android.R.layout.simple_list_item_1,
subjects
);

listViewSubjects.setAdapter(adapter);
}
}
11. 11 write a program to implement concept of checkbox for hobby selection
display value of checkboxes on click of button.txt
Java Code (MainActivity.java):
java
Copy code
package com.example.hobbyselection;

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

public class MainActivity extends AppCompatActivity {

CheckBox checkBoxReading, checkBoxMusic, checkBoxSports, checkBoxTraveling;


Button showButton;
TextView resultTextView;

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

// Initialize CheckBoxes, Button and TextView


checkBoxReading = findViewById(R.id.checkBoxReading);
checkBoxMusic = findViewById(R.id.checkBoxMusic);
checkBoxSports = findViewById(R.id.checkBoxSports);
checkBoxTraveling = findViewById(R.id.checkBoxTraveling);
showButton = findViewById(R.id.showButton);
resultTextView = findViewById(R.id.resultTextView);

// Set OnClickListener for the Button


showButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuilder selectedHobbies = new StringBuilder("Selected Hobbies:\n");

// Check which hobbies are selected


if (checkBoxReading.isChecked()) {
selectedHobbies.append("Reading\n");
}
if (checkBoxMusic.isChecked()) {
selectedHobbies.append("Music\n");
}
if (checkBoxSports.isChecked()) {
selectedHobbies.append("Sports\n");
}
if (checkBoxTraveling.isChecked()) {
selectedHobbies.append("Traveling\n");
}

// If no hobby is selected, show a Toast message


if (selectedHobbies.toString().equals("Selected Hobbies:\n")) {
Toast.makeText(MainActivity.this, "No hobbies selected!",
Toast.LENGTH_SHORT).show();
} else {
// Display selected hobbies
resultTextView.setText(selectedHobbies.toString());
}
}
});
}
}
XML Code (activity_main.xml):
xml
Copy 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:padding="16dp"
android:gravity="center">

<!-- CheckBox for Reading hobby -->


<CheckBox
android:id="@+id/checkBoxReading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reading" />

<!-- CheckBox for Music hobby -->


<CheckBox
android:id="@+id/checkBoxMusic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Music" />

<!-- CheckBox for Sports hobby -->


<CheckBox
android:id="@+id/checkBoxSports"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sports" />

<!-- CheckBox for Traveling hobby -->


<CheckBox
android:id="@+id/checkBoxTraveling"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Traveling" />

<!-- Button to display selected hobbies -->


<Button
android:id="@+id/showButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected Hobbies"
android:layout_marginTop="20dp" />

<!-- TextView to display the result -->


<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
android:layout_marginTop="20dp" />

</LinearLayout>

12. 12 write a program to show current date (datemonthyear).txt


Java Code (MainActivity.java):
java
Copy code
package com.example.datepickerexample;

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

public class MainActivity extends AppCompatActivity {

DatePicker datePicker;
Button showButton;
TextView dateTextView;

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

// Initialize the DatePicker, Button, and TextView


datePicker = findViewById(R.id.datePicker);
showButton = findViewById(R.id.showButton);
dateTextView = findViewById(R.id.dateTextView);

// Set an OnClickListener on the button to show the selected date


showButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the selected date from the DatePicker
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth() + 1; // Month is zero-indexed
int year = datePicker.getYear();

// Format the date in "day/month/year" format


String selectedDate = day + "/" + month + "/" + year;

// Display the selected date in the TextView


dateTextView.setText("Selected Date: " + selectedDate);
}
});
}
}
XML Code (activity_main.xml):
xml
Copy 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:padding="16dp"
android:gravity="center">

<!-- DatePicker widget to select the date -->


<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:calendarViewShown="false"
android:datePickerMode="spinner" />

<!-- Button to show the selected date -->


<Button
android:id="@+id/showButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected Date"
android:layout_marginTop="20dp" />

<!-- TextView to display the selected date -->


<TextView
android:id="@+id/dateTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Selected Date: "
android:textSize="18sp"
android:layout_marginTop="20dp" />

</LinearLayout>

13. 13 write a program to show current time using TimePicker .txt


Java Code (MainActivity.java):
java
Copy code
package com.example.timepickerexample;

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

public class MainActivity extends AppCompatActivity {

TimePicker timePicker;
Button showButton;
TextView timeTextView;

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

// Initialize the TimePicker, Button, and TextView


timePicker = findViewById(R.id.timePicker);
showButton = findViewById(R.id.showButton);
timeTextView = findViewById(R.id.timeTextView);

// Set the current time to the TimePicker


timePicker.setIs24HourView(true); // Optional: Set 24-hour format
// Get the current hour and minute and set the TimePicker
java.util.Calendar calendar = java.util.Calendar.getInstance();
timePicker.setCurrentHour(calendar.get(java.util.Calendar.HOUR_OF_DAY));
timePicker.setCurrentMinute(calendar.get(java.util.Calendar.MINUTE));

// Set an OnClickListener on the button to show the selected time


showButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the selected time from the TimePicker
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();

// Format the time in "hour:minute" format


String selectedTime = String.format("%02d:%02d", hour, minute);
// Display the selected time in the TextView
timeTextView.setText("Selected Time: " + selectedTime);
}
});
}
}
XML Code (activity_main.xml):
xml
Copy 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:padding="16dp"
android:gravity="center">

<!-- TimePicker widget to select the time -->


<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"
android:is24HourView="true" />

<!-- Button to show the selected time -->


<Button
android:id="@+id/showButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected Time"
android:layout_marginTop="20dp" />

<!-- TextView to display the selected time -->


<TextView
android:id="@+id/timeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Selected Time: "
android:textSize="18sp"
android:layout_marginTop="20dp" />
</LinearLayout>

14. 14 write a progra0m to implement concept of activity lifecycle.txt


Java Code (MainActivity.java):
java
Copy code
package com.example.activitylifecycleexample;

import android.os.Bundle;
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);
Toast.makeText(this, "onCreate called", Toast.LENGTH_SHORT).show(); // Toast in
onCreate
}

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

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

@Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "onPause called", Toast.LENGTH_SHORT).show(); // Toast in
onPause
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "onStop called", Toast.LENGTH_SHORT).show(); // Toast in
onStop
}

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

@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "onDestroy called", Toast.LENGTH_SHORT).show(); // Toast in
onDestroy
}
}
XML Code (activity_main.xml):
xml
Copy 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:padding="16dp"
android:gravity="center">

<!-- TextView or other UI elements can be added here if needed -->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity Lifecycle Example"
android:textSize="18sp"
android:textAlignment="center" />
</LinearLayout>
15. 15 write a program to implement concept of service use the easiest to
implement service.txt
Java Code:
MainActivity.java
java
Copy code
package com.example.simplebackgroundservice;

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

public class MainActivity extends AppCompatActivity {

Button startServiceButton, stopServiceButton;

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

startServiceButton = findViewById(R.id.startServiceButton);
stopServiceButton = findViewById(R.id.stopServiceButton);

// Start the service when the button is clicked


startServiceButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent serviceIntent = new Intent(MainActivity.this, SimpleService.class);
startService(serviceIntent);
Toast.makeText(MainActivity.this, "Service Started",
Toast.LENGTH_SHORT).show();
}
});

// Stop the service when the button is clicked


stopServiceButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent serviceIntent = new Intent(MainActivity.this, SimpleService.class);
stopService(serviceIntent);
Toast.makeText(MainActivity.this, "Service Stopped",
Toast.LENGTH_SHORT).show();
}
});
}
}
SimpleService.java
java
Copy code
package com.example.simplebackgroundservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Handler;
import android.widget.Toast;

public class SimpleService extends Service {

private Handler handler = new Handler();


private Runnable runnable;

@Override
public void onCreate() {
super.onCreate();
// Initialize the Runnable to show Toast every 5 seconds
runnable = new Runnable() {
@Override
public void run() {
Toast.makeText(SimpleService.this, "Service is Running",
Toast.LENGTH_SHORT).show();
handler.postDelayed(this, 5000); // Show toast every 5 seconds
}
};
handler.post(runnable); // Start running the task
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Return START_STICKY to keep the service running even if it gets stopped
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null; // This service is not bindable
}

@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(runnable); // Stop the handler when the service is destroyed
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
}
}
XML Code:
activity_main.xml
xml
Copy 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:gravity="center"
android:padding="16dp">

<!-- Button to start the service -->


<Button
android:id="@+id/startServiceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service" />

<!-- Button to stop the service -->


<Button
android:id="@+id/stopServiceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service"
android:layout_marginTop="20dp" />

</LinearLayout>
How to Run:
Create a new Android project in Android Studio.
Replace the content of MainActivity.java, SimpleService.java, and activity_main.xml with the
provided code.

Add the necessary permission in the AndroidManifest.xml to declare the service:

xml
Copy code
<service android:name=".SimpleService" />
Run the app on an emulator or a physical device.

When you press the "Start Service" button, the service starts and displays a toast every 5
seconds.

When you press the "Stop Service" button, the service stops, and the toasts will stop
appearing.

Let me know if you need any changes or further explanations!

16. 16 write a program to play audio in android.txt


Java Code:
MainActivity.java
java
Copy code
package com.example.audioplayerexample;

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

public class MainActivity extends AppCompatActivity {

private MediaPlayer mediaPlayer;


private Button startButton, pauseButton, stopButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize buttons
startButton = findViewById(R.id.startButton);
pauseButton = findViewById(R.id.pauseButton);
stopButton = findViewById(R.id.stopButton);

// Initialize MediaPlayer with an audio file


mediaPlayer = MediaPlayer.create(this, R.raw.sample_audio); // Add your audio file in
the 'res/raw' folder

// Start the audio when the Start button is clicked


startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
Toast.makeText(MainActivity.this, "Audio Started",
Toast.LENGTH_SHORT).show();
}
}
});

// Pause the audio when the Pause button is clicked


pauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
Toast.makeText(MainActivity.this, "Audio Paused",
Toast.LENGTH_SHORT).show();
}
}
});

// Stop the audio when the Stop button is clicked


stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer.isPlaying() || mediaPlayer.isPaused()) {
mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.sample_audio); //
Reset the player
Toast.makeText(MainActivity.this, "Audio Stopped",
Toast.LENGTH_SHORT).show();
}
}
});
}

@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release(); // Release the MediaPlayer when the activity is destroyed
}
}
}
XML Code:
activity_main.xml
xml
Copy 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:gravity="center"
android:padding="16dp">

<!-- Button to start the audio -->


<Button
android:id="@+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Audio"
android:layout_marginBottom="20dp" />

<!-- Button to pause the audio -->


<Button
android:id="@+id/pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause Audio"
android:layout_marginBottom="20dp" />

<!-- Button to stop the audio -->


<Button
android:id="@+id/stopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Audio" />

</LinearLayout>

17. 17 write a program to play video in android.txt


Java Code:
MainActivity.java
java
Copy code
package com.example.videoplayerexample;

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

public class MainActivity extends AppCompatActivity {

private VideoView videoView;


private Button startButton;

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

// Initialize VideoView and Button


videoView = findViewById(R.id.videoView);
startButton = findViewById(R.id.startButton);

// Set the path to the video file (can be from raw folder, URL, etc.)
String videoPath = "android.resource://" + getPackageName() + "/" +
R.raw.sample_video;
videoView.setVideoPath(videoPath);

// Create a MediaController to add playback controls


MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);

// Set the MediaController to the VideoView


videoView.setMediaController(mediaController);

// Start the video when the Start button is clicked


startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
videoView.start();
Toast.makeText(MainActivity.this, "Video Started", Toast.LENGTH_SHORT).show();
}
});
}

@Override
protected void onPause() {
super.onPause();
// Pause the video when the activity is paused
if (videoView.isPlaying()) {
videoView.pause();
}
}

@Override
protected void onDestroy() {
super.onDestroy();
// Release the video resources when the activity is destroyed
videoView.stopPlayback();
}
}
XML Code:
activity_main.xml
xml
Copy 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:gravity="center"
android:padding="16dp">
<!-- VideoView to display the video -->
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="300dp" />

<!-- Button to start the video -->


<Button
android:id="@+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Video"
android:layout_marginTop="20dp" />

</LinearLayout>

18. 18 write a program to capture image in android .txt


XML Code:
activity_main.xml
xml
Copy 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:gravity="center"
android:padding="16dp">

<!-- Button to capture the image -->


<Button
android:id="@+id/captureButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture Image" />

<!-- ImageView to display the captured image -->


<ImageView
android:id="@+id/imageView"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginTop="20dp"
android:contentDescription="Captured Image"
android:scaleType="centerCrop" />

</LinearLayout>
MainActivity.java
java
Copy code
package com.example.captureimageexample;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private static final int REQUEST_IMAGE_CAPTURE = 1;


private Button captureButton;
private ImageView imageView;

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

// Initialize UI components
captureButton = findViewById(R.id.captureButton);
imageView = findViewById(R.id.imageView);

// Set onClickListener for the Capture button


captureButton.setOnClickListener(v -> {
// Create an Intent to open the camera
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Start the camera activity and wait for the result
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} else {
Toast.makeText(MainActivity.this, "Camera not available",
Toast.LENGTH_SHORT).show();
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

// Check if the image capture was successful


if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// Get the captured image as a Bitmap using getExtras().get("data")
Bitmap photo = (Bitmap) data.getExtras().get("data");

// Display the captured image in the ImageView


imageView.setImageBitmap(photo);
}
}
}
Permissions:
To request the camera permission, you need to add the required permission to the
AndroidManifest.xml.

Add Camera Permission:


xml
Copy code
<uses-permission android:name="android.permission.CAMERA" />

19. 19 write a program to turn on and turn off bluetooth in android.txt


XML Code:
activity_main.xml
xml
Copy 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:gravity="center"
android:padding="16dp">

<!-- Button to turn on Bluetooth -->


<Button
android:id="@+id/turnOnButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On Bluetooth" />

<!-- Button to turn off Bluetooth -->


<Button
android:id="@+id/turnOffButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn Off Bluetooth"
android:layout_marginTop="20dp" />

</LinearLayout>

Permissions:
To manage Bluetooth, you need to include Bluetooth-related permissions in the
AndroidManifest.xml.

Add Permissions:
xml
Copy code
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
MainActivity.java
java
Copy code
package com.example.bluetoothapp;

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

public class MainActivity extends AppCompatActivity {

private BluetoothAdapter bluetoothAdapter;


private Button turnOnButton;
private Button turnOffButton;

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

// Initialize BluetoothAdapter
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// Initialize UI components
turnOnButton = findViewById(R.id.turnOnButton);
turnOffButton = findViewById(R.id.turnOffButton);

// Check if Bluetooth is supported


if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device",
Toast.LENGTH_SHORT).show();
} else {
// Set OnClickListener for Turn On Bluetooth button
turnOnButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable(); // Enable Bluetooth
Toast.makeText(MainActivity.this, "Bluetooth Enabled",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Bluetooth is already on",
Toast.LENGTH_SHORT).show();
}
}
});

// Set OnClickListener for Turn Off Bluetooth button


turnOffButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable(); // Disable Bluetooth
Toast.makeText(MainActivity.this, "Bluetooth Disabled",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Bluetooth is already off",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
}

20. 20 write a program to implement TextToSpeech .txt


activity_main.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">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Text"
android:hint="Enter Any Sentence" />
<Button
android:layout_width="wrap_content"
android:id="@+id/btnText"
android:layout_height="wrap_content"
android:text="Click Here"
android:layout_gravity="center"/>
</LinearLayout>
MainActivity.java
package com.example.texttospeechdemo;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.speech.tts.TextToSpeech;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.texttospeechdemo.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
public class MainActivity extends AppCompatActivity
{
EditText Text;
Button btnText;
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Text = findViewById(R.id.Text);
btnText = findViewById(R.id.btnText);
textToSpeech = new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener()
{
@Override
public void onInit(int i)
{
if(i!=TextToSpeech.ERROR)
{
textToSpeech.setLanguage(Locale.ENGLISH);
}
}
});
btnText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textToSpeech.speak(Text.getText().toString(),TextToSpeech.QUEUE_FLUSH,null);
}
});
}
}
<uses-permission android:name="android.permission.INTERNET"/>

21. 21 write program to semd sms.txt


Complete example
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="Mobile No" />
<EditText
android:id="@+id/mblTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/msgTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Send SMS" />
</LinearLayout>
MainActivity.java
package com.example.sendsmsexample;
import android.content.Intent;
import android.net.Uri;
import android.provider.Telephony;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText txtMobile;
private EditText txtMessage;
private Button btnSms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtMobile = (EditText)findViewById(R.id.mblTxt);
txtMessage = (EditText)findViewById(R.id.msgTxt);
btnSms = (Button)findViewById(R.id.btnSend);

btnSms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(txtMobile.getText().toString(),null,txtMessage
.getText().toString(),null,null);
Toast.makeText(MainActivity.this, "SMS Sent Successfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "SMS Failed to Send, Please try
again", Toast.LENGTH_SHORT).show();
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sendsmsexample">
<uses-permission android:name="android.permission.SEND_SMS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

22. 22 write a program to send email.txt


Program to send Email
<?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">

<EditText
android:id="@+id/editText1"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Send To" />

<EditText
android:id="@+id/editText2"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Subject" />

<EditText
android:id="@+id/editText3"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Body (Message)" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send email!!" />
</LinearLayout>

package com.example.demo;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

// Declare EditText and Button objects


private Button button;
private EditText sendTo;
private EditText subject;
private EditText body;

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

// Initialize EditText and Button


sendTo = findViewById(R.id.editText1);
subject = findViewById(R.id.editText2);
body = findViewById(R.id.editText3);
button = findViewById(R.id.button);

// Set OnClickListener for the button


button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String emailSend = sendTo.getText().toString();
String emailSubject = subject.getText().toString();
String emailBody = body.getText().toString();

// Define Intent object with action attribute as ACTION_SEND


Intent intent = new Intent(Intent.ACTION_SEND);

// Add email details using putExtra


intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailSend});
intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
intent.putExtra(Intent.EXTRA_TEXT, emailBody);
// Set the type of intent
intent.setType("message/rfc822");

// Start the activity with a chooser for email clients


startActivity(Intent.createChooser(intent, "Choose an Email client :"));
}
});
}
}

23. 23 write a program to display a marker on nashik location.txt


Steps:
Set up Google Maps API Key: You need to get a Google Maps API key and add it to your
project.

Create a simple map activity using SupportMapFragmentActivity and OnMapReadyCallback.

Place a marker on the map at the coordinates of Nashik (19.9975° N, 73.7901° E).

1. Set up Google Maps API in AndroidManifest.xml:


xml
Copy code
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOUR_API_KEY_HERE"/>

<activity
android:name=".MapsActivity"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Replace "YOUR_API_KEY_HERE" with your actual Google Maps API Key.

2. Create MapsActivity.java to load the map and add the marker:


MapsActivity.java
java
Copy code
package com.example.mapsapp;

import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

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

// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

// Nashik coordinates
LatLng nashik = new LatLng(19.9975, 73.7901);

// Add a marker for Nashik


mMap.addMarker(new MarkerOptions().position(nashik).title("Marker in Nashik"));
// Move the camera to Nashik and set zoom level
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(nashik, 12));
}
}
3. Create the Layout for activity_maps.xml:
activity_maps.xml
xml
Copy code
<?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">

<!-- Google Map Fragment -->


<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
4. Add Google Play Services Dependency in build.gradle:
Add the following dependencies to your app/build.gradle file:

gradle
Copy code
dependencies {
implementation 'com.google.android.gms:play-services-maps:17.0.1'
}

24. 24 write a program for displaying current location of user.txt


activity_main

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="current location"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BTN"
android:id="@+id/btn"/>

</LinearLayout>

MainActivity.java
package com.example.myapplication;

import android.content.Context;
import android.location.*;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity implements LocationListener{

Button btn;
TextView txt;
LocationManager lm;

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

btn=findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getMyLocation();
}
});
}
public void getMyLocation(){

try {
lm=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (lm != null) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
}
} else {
showToast("Location permission not granted");
}

}
catch(Exception e)
{
showToast("Errorr");
}
}

public void onProviderEnabled(String Provider)


{
showToast("Provider Enabled ");
}
public void onProviderDisabled(String provider)
{
showToast("Provider disabled");
}
public void onStatusChanged(String provider,int status,Bundle extras)
{
showToast("Status changed");
}
@Override
public void onLocationChanged(@NonNull Location location) {
showToast("Latitude = "+location.getLatitude()+" Longitude -=
"+location.getLongitude());
}
public void showToast(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>
25. 25 write a program to implement light sensor display lux value.txt
MainActivity.java
package com.example.lightsensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

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

SensorManager sm=(SensorManager) getSystemService(Context.SENSOR_SERVICE);

Sensor light=sm.getDefaultSensor(Sensor.TYPE_LIGHT);

sm.registerListener(new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float lux=event.values[0];
Toast.makeText(getApplicationContext(),"Light sensor lux=
"+lux,Toast.LENGTH_LONG).show();
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
},light,sm.SENSOR_DELAY_NORMAL);
}
}

activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

</LinearLayout>

26. 26 write a program to implement accelerometer and display x y z values.txt


MainActivity.java
package com.example.accerelometersensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

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

SensorManager sm=(SensorManager) getSystemService(Context.SENSOR_SERVICE);


Sensor accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float x=event.values[0];
float y=event.values[1];
float z=event.values[2];
Toast.makeText(getApplicationContext(),"x = "+x+" y = "+y+" z =
"+z,Toast.LENGTH_LONG).show();
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
},accelerometer,sm.SENSOR_DELAY_NORMAL);
}
}
activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

</LinearLayout>

27. 27 write a program to implement fade in and fade out animation apply it on
image and when user will click on Buttons respectively.txt
1. Create the Animation Files (fade_in.xml and fade_out.xml)
Create two animation files in the res/anim/ directory:

fade_in.xml
xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="1000" />
This XML file defines an alpha animation that changes the opacity from 0 (invisible) to 1
(fully visible) over 1 second (1000ms).

fade_out.xml
xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="1000" />
This XML file defines an alpha animation that changes the opacity from 1 (fully visible) to 0
(invisible) over 1 second.

2. Create the Layout File (activity_main.xml)


In this layout, we have an ImageView and two buttons (Fade In and Fade Out).

activity_main.xml
xml
Copy 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:padding="16dp"
android:gravity="center">

<!-- ImageView to apply fade-in and fade-out effects -->


<ImageView
android:id="@+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/your_image" <!-- Replace with your image -->
android:visibility="invisible" />

<!-- Button to trigger fade-in -->


<Button
android:id="@+id/fadeInButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fade In" />

<!-- Button to trigger fade-out -->


<Button
android:id="@+id/fadeOutButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fade Out" />
</LinearLayout>
The ImageView initially has visibility="invisible" to make it hidden at first.

Two buttons (Fade In and Fade Out) are provided for triggering the respective animations.

3. Apply Animations in MainActivity.java


In MainActivity, we will load the animations using AnimationUtils.loadAnimation() and set
an OnClickListener for each button to apply the respective animation.

MainActivity.java
java
Copy code
package com.example.fadeinoutanimation;

import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private ImageView imageView;


private Button fadeInButton, fadeOutButton;

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

// Initialize the ImageView and Buttons


imageView = findViewById(R.id.imageView);
fadeInButton = findViewById(R.id.fadeInButton);
fadeOutButton = findViewById(R.id.fadeOutButton);

// Load animations
final Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
final Animation fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);

// Button click listener to trigger fade-in


fadeInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView.setVisibility(View.VISIBLE); // Make the image visible
imageView.startAnimation(fadeIn); // Start fade-in animation
}
});

// Button click listener to trigger fade-out


fadeOutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView.startAnimation(fadeOut); // Start fade-out animation
imageView.setVisibility(View.INVISIBLE); // Make the image invisible after
animation
}
});
}
}

28. 28 write a program to place 4 buttons in 4 corner of screen using


RelativeLayout place 5th Button at the center of screen.txt
XML Layout (activity_main.xml)
xml
Copy code
<?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">

<!-- Button in the Top-Left Corner -->


<Button
android:id="@+id/buttonTopLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Top Left"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_margin="16dp" />

<!-- Button in the Top-Right Corner -->


<Button
android:id="@+id/buttonTopRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Top Right"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp" />

<!-- Button in the Bottom-Left Corner -->


<Button
android:id="@+id/buttonBottomLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bottom Left"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_margin="16dp" />

<!-- Button in the Bottom-Right Corner -->


<Button
android:id="@+id/buttonBottomRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bottom Right"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp" />

<!-- Button at the Center -->


<Button
android:id="@+id/buttonCenter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Center"
android:layout_centerInParent="true" />

</RelativeLayout>
package com.example.cornerbuttonlayout;

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

public class MainActivity extends AppCompatActivity {

private Button buttonTopLeft, buttonTopRight, buttonBottomLeft, buttonBottomRight,


buttonCenter;

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

}
}

29. 29 write a program to display all sensors .txt


XML Layout (activity_main.xml)
xml
Copy 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:padding="16dp">

<TextView
android:id="@+id/sensorsTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sensors List"
android:textSize="18sp"
android:scrollbars="vertical"
android:layout_marginTop="16dp" />
</LinearLayout>
Java Code (MainActivity.java)
java
Copy code
package com.example.sensorslist;

import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private TextView sensorsTextView;


private SensorManager sensorManager;

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

// Initialize the TextView and SensorManager


sensorsTextView = findViewById(R.id.sensorsTextView);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

// Get the list of all sensors


if (sensorManager != null) {
// Get the list of all available sensors
java.util.List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);

StringBuilder sensors = new StringBuilder();


for (Sensor sensor : sensorList) {
// Append each sensor's name to the StringBuilder
sensors.append(sensor.getName()).append("\n");
}

// Set the list of sensors in the TextView


sensorsTextView.setText(sensors.toString());
}
}
}
30. 30 write a program to implement custom toast message display message
with image and text.txt
XML Layout for Custom Toast (toast_layout.xml)
This XML layout contains both an image and a text that will be displayed in the custom
Toast.

xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp"
android:background="@drawable/toast_background"
android:gravity="center">

<!-- Image to be shown in the Toast -->


<ImageView
android:id="@+id/toastImage"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/ic_launcher_foreground"
android:layout_marginEnd="10dp" />

<!-- Text to be shown in the Toast -->


<TextView
android:id="@+id/toastText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Toast Message"
android:textSize="16sp"
android:textColor="#FFFFFF" />
</LinearLayout>
activity_main.xml)
This layout contains a Button that will trigger the custom Toast when clicked.

xml
Copy 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:padding="16dp"
android:gravity="center">

<!-- Button to trigger custom toast -->


<Button
android:id="@+id/showToastButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Custom Toast"
android:textSize="18sp"
android:layout_marginBottom="16dp" />

</LinearLayout>

(MainActivity.java)
Now we set the OnClickListener on the Button to display the custom Toast when clicked.

java
Copy code
package com.example.customtoast;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
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);

// Get the reference of the button


Button showToastButton = findViewById(R.id.showToastButton);

// Set an OnClickListener for the button to show custom toast


showToastButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Call the method to show custom toast
showCustomToast();
}
});
}

private void showCustomToast() {


// Inflate the custom layout for Toast
LayoutInflater inflater = getLayoutInflater();
View customView = inflater.inflate(R.layout.toast_layout, null);

// Set the text for the Toast


TextView toastText = customView.findViewById(R.id.toastText);
toastText.setText("This is a custom Toast!");

// Set the image for the Toast (you can change the image resource as per your need)
ImageView toastImage = customView.findViewById(R.id.toastImage);
toastImage.setImageResource(R.drawable.ic_launcher_foreground);

// Create the Toast with the custom view


Toast customToast = new Toast(getApplicationContext());
customToast.setDuration(Toast.LENGTH_LONG);
customToast.setView(customView);

// Show the Toast


customToast.show();
}
}

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