ANDROID DEVELOPMENT
XML full form → eXtensible Markup Language
In Android:
It is used to design how your app looks.
You arrange buttons, text, images, etc. using XML.
It’s like creating a blueprint of your app's screen.
Only design, no working or logic (logic is done in Java/Kotlin).
[Link] Layouts Basics
<RelativeLayout> → It is a type of layout in XML.
Meaning:
It arranges views (buttons, text, images) relative to each other.
Example:
o One button below a text.
o One image center of screen.
Example
<RelativeLayout
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
You are starting a RelativeLayout
xmlns:android="[Link]
👉 This is telling Android that "I am using Android's official rules for XML."
👉 Without it, Android won't understand your XML
xmlns:app="[Link]
👉 This is for custom features (like when you use special things like Material Design, etc.).
👉 For now, you can ignore it. It's like extra tools.
xmlns:tools="[Link]
👉 Only used to show preview correctly in Android Studio.
👉 It doesn’t go inside your real app when you run it , Only for help in design view.
android:id="@+id/main"
👉 You are giving a name (id) to this layout: main.
👉 Later you can find this layout in your Java/Kotlin code using this ID.
android:layout_width="match_parent"
android:layout_height="match_parent"
👉 Width and height of layout will cover the whole screen.
tools:context=".MainActivity">
👉 Tells preview that this layout belongs to your [Link] (or .kt) file.
👉 Only for help while designing — not used in real app while running.
For width and height in Android XML :
1. match_parent
👉 Means take full size of the parent.
👉 Example: Fill full screen width or height.
2. wrap_content
👉 Means only take as much space as needed.
👉 Example: Button will be only as big as its text.
3. Exact value (like 200dp)
👉 You can fix a size.
👉 Example: Make a button exactly 200 dp wide or 150 dp tall.
android:layout_width="200dp"
android:layout_height="150dp"
child property of RelativeLayout
Aligning Views
Align to top → android:layout_alignParentTop="true"
Align to bottom → android:layout_alignParentBottom="true"
Align to start → android:layout_alignParentStart="true"
Align to end → android:layout_alignParentEnd="true"
Align with parent → android:layout_alignWithParentIfMissing="true"
Positioning Relative to Other Views
Above another view → android:layout_above="@id/otherViewId"
Below another view → android:layout_below="@id/otherViewId"
To left of another view → android:layout_toLeftOf="@id/otherViewId"
To right of another view → android:layout_toRightOf="@id/otherViewId"
Margins and Spacing
Margin top → android:layout_marginTop="16dp"
Margin bottom → android:layout_marginBottom="16dp"
Margin start → android:layout_marginStart="16dp"
Margin end → android:layout_marginEnd="16dp"
All margins → android:layout_margin="16dp"
Width and Height
Wrap content → android:layout_width="wrap_content",
android:layout_height="wrap_content"
Match parent → android:layout_width="match_parent",
android:layout_height="match_parent"
[Link] Basics
<LinearLayout> → Used to arrange views in a single row or column.
Orientation
Horizontal → Arranges views left to right: android:orientation="horizontal"
Vertical → Arranges views top to bottom: android:orientation="vertical"
Weight
layout_weight → Distributes extra space evenly between views.
Example: android:layout_weight="1"
Aligning Views
Align to start → Aligns view to left (LTR) or right (RTL): android:gravity="start"
Align to center → Centers the view inside: android:gravity="center"
Align to end → Aligns view to right (LTR) or left (RTL): android:gravity="end"
Padding and Margins
Padding → Adds space inside the view: android:padding="16dp"
Margin → Adds space outside the view: android:layout_margin="16dp"
[Link] Basics
GridLayout arranges its children in a grid — with rows and columns, just like a table or Excel
sheet.
You define how many rows and columns you want.
Each child can be placed in a specific cell.
You can even make children span multiple rows or columns.
✅ Key Properties
android:rowCount – Total number of rows.
android:columnCount – Total number of columns.
layout_row – Row index of the view.
layout_column – Column index of the view.
layout_rowSpan / layout_columnSpan – If a view should span multiple rows or
columns.
Views
In Android, views are the building blocks of UI components. Each view represents a single
element on the screen, such as a button, text, image, etc.
Types of Views Summary:
Basic views: TextView, Button, ImageView, EditText, CheckBox, RadioButton, Switch.
Containers: LinearLayout, RelativeLayout, FrameLayout, GridLayout,
ConstraintLayout, ScrollView.
Specialized Views: ProgressBar, ImageButton, TextInputLayout.
📚 Basic Views:
TextView → Displays text.
➔ <TextView />
Button → A clickable button for actions.
➔ <Button />
ImageView → Displays an image.
➔ <ImageView />
EditText → Editable text field for user input.
➔ <EditText />
CheckBox → A small box that can be checked or unchecked.
➔ <CheckBox />
RadioButton → Used to select one option from multiple options.
➔ <RadioButton />
Switch → A toggle button (on/off).
➔ <Switch />
ProgressBar → Shows loading/progress status.
➔ <ProgressBar />
ImageButton → A button with an image instead of text.
➔ <ImageButton />
📚 Container Views (Layouts):
LinearLayout → Arranges child views in a row or column.
➔ <LinearLayout />
RelativeLayout → Arranges child views relative to each other.
➔ <RelativeLayout />
ConstraintLayout → Flexible layout to place views using constraints.
➔ <[Link] />
FrameLayout → Places child views on top of each other like layers.
➔ <FrameLayout />
GridLayout → Arranges child views in rows and columns (grid system).
➔ <GridLayout />
ScrollView → Makes the child views scroll vertically if needed.
➔ <ScrollView />
Main Android Components (Core Parts of Any App):
1. Activity → A screen in your app (like MainActivity).
➤ Example: When you open the app, you're seeing an activity.
2. Service → Runs in background (no UI).
➤ Example: Playing music in background, downloading file.
3. Broadcast Receiver → Listens to system or app-wide events.
➤ Example: Low battery alert, incoming call, network change.
4. Content Provider → Shares data between apps.
➤ Example: Your Contacts app uses a content provider to give contact info to
WhatsApp.
[Link]
➤public class MainActivity extends AppCompatActivity {
This is your main screen class (Activity) and it uses features from Android’s
AppCompatActivity.
➤protected void onCreate(Bundle savedInstanceState)
This runs when your app screen starts. It's like a setup() function.
➤[Link](savedInstanceState);
It runs the default setup from the parent class. Required always.
➤[Link](this);
It makes your app use full screen (under status bar, nav bar).
➤setContentView([Link].activity_main);
This tells Android: “use activity_main.xml layout” for this screen.
➤ [Link](...)
This helps adjust your layout when system bars (like status bar) overlap.
Example: it adds padding to avoid your views being under the notch or nav bar.
BMI CALCULATOR
[Link] Views:
Button btnCalculate;
TextView txtResult;
[Link] View by ID:
btnCalculate = findViewById([Link]);
txtResult = findViewById([Link]);
[Link] OnClickListener (Button):
[Link](new [Link]() {
@Override
public void onClick(View v) {
int wt = [Link]([Link]().toString());
[Link]("BMI: " + wt); // Just an example to show setting text
}});
4. Getting and Setting Text (EditText and TextView)
Get text from EditText:
int wt = [Link]([Link]().toString());
Set text to TextView:
[Link]("Your result: " + bmi);
5. Setting Background Color
To set the background color dynamically, main is LinearLayout Reference .
[Link](getResources().getColor([Link]));
6. Converting User Input (Integer, Double)
Convert from EditText input (String to Integer):
int wt = [Link]([Link]().toString());
📘 Intent Passing in Android (Starting a New Activity)
Intent is used to navigate from one activity to another. It tells Android, "Hey, I want to go
from this screen to that one."
Intent i = new Intent([Link], [Link]);
Button btn = findViewById([Link]); // Step 1: Get the button
Intent iNext = new Intent([Link], [Link]); // Step 2:
Create intent (source to destination)
[Link](new [Link]() {
@Override
public void onClick(View v) {
startActivity(iNext); // Step 3: Start the second activity
}
});
📝 Note : You must declare second activity in your
[Link]:
All Activities are shown , select any one to create new scene or
Activity.
🧠 Key Points to Remember
Always place this code inside onCreate() so it runs when the activity is being created.
new Intent([Link], [Link]) → tells Android: go from MainActivity to
second.
startActivity(iNext) → actually launches the second activity.
This is how you navigate between screens in an app.
Bundle Passing (Intent Extras)
Use [Link]() to send data → use getIntent().getXXXExtra() to receive it
in the next Activity.
✅ Send data from one Activity to another:
Intent intent = new Intent([Link], [Link]);
[Link]("title", "Student Info");
[Link]("StudentName", "John");
[Link]("Rollno", 42);
startActivity(intent);
✅ Receive data in next Activity:
Intent fromAct = getIntent();
String title = [Link]("title");
String name = [Link]("StudentName");
int Rollno = [Link]("Rollno", 0);
✅ Update UI:
TextView txtStudentinfo = findViewById([Link]);
String str = "Rollno: " + Rollno + " Name: " + name;
[Link](str);
✅ Set ActionBar title:
getSupportActionBar().setTitle(title);
Splash Screen (first Loading screen)
✅ Step 1: Change Splash activity as the starting (launcher) activity in [Link]
In [Link], inside <application>, we write:
<activity
android:name=".Splash"
android:exported="true"
android:theme="@style/[Link]">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
✅ Why:
The <intent-filter> with MAIN and LAUNCHER tells Android → “this is the first screen when
the app starts.”
Without this, the app won’t know which screen to open first.
✅ Step 2: Understand important functions in [Link]
Intent iHome = new Intent([Link], [Link]);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startActivity(iHome);
finish();
}
}, 5000);
🔑 Important parts and why we use them:
1. Intent iHome = new Intent([Link], [Link]);
→ Creates an Intent object, which is used to tell Android we want to move from
Splash to MainActivity.
→ Think of it like preparing a ticket for MainActivity.
2. new Handler().postDelayed(new Runnable() { ... }, 5000);
→ Sets a delay of 5000 milliseconds (5 seconds) before running the code inside.
→ This is what makes the splash screen stay visible for 5 seconds before switching
screens.
3. startActivity(iHome);
→ Starts MainActivity using the Intent we prepared.
4. finish();
→ Closes the Splash activity so that when the user presses the back button, they
won’t return to the splash screen.
Animations
Make a directory in resource folder and
name it anim or choose value as anim
then make a new animation and
name it.
Make 1st animation , name it
translate
[Link]
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="[Link]
<scale
android:fromXScale="1"
android:fromYScale="1"
android:toXScale="3"
android:toYScale="3"
android:pivotY="50%"
android:pivotX="50%"
android:duration="3000"
/>
</set>
[Link]
TextView txtanim;
Button btnTranslate,btnRotate,btnScale,btnAlpha;
txtanim=findViewById([Link].txt1);
btnTranslate=findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
Animation move =
[Link](getApplicationContext(),[Link]);
[Link](move);
}
});
You declare TextView and Button variables (txtanim, btnTranslate).
You connect them to the UI using findViewById( ).
You set an onClickListener on the Translate button → when clicked, it loads the move
animation from res/anim/[Link]
and starts the animation on the txtanim TextView.
Lottie Animation
link : [Link]
Download any animation in lottie JSON format
make raw directory as we made of anim, in res folder , then copy that JSON and
click on raw and ctrl+v(paste)
then find dependency here link: [Link]
Scroll down to find the dependency and check the current lottie version there
dependencies {
implementation '[Link]:lottie:$lottieVersion'
}
current version : [Link]
In android studio go to Gradle scripts->[Link] (Module app)
then paste in dependencies
implementation("[Link]:lottie:6.6.6") replace latest version
or do implementation([Link])
Then if sync option is coming then do that.
In xml : it will play automatically
<[Link]
android:layout_width="300dp"
android:layout_height="300dp"
app:lottie_rawRes="@raw/anmlottie"
app:lottie_autoPlay="true"
app:lottie_loop="true"
/>
<
If you want manual control then
LottieAnimationView laview;
//control manually
[Link]([Link]); //anmlottie rawfile
[Link]();
[Link](true);
List Views :
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listview"
/>
This puts a ListView on your screen — it’s like a scrollable list where you can show multiple
items (like names, contacts, etc.).
In [Link]
[Link] ListView from XML to Java
lv = findViewById([Link]);
[Link] a list of names
ArrayList<String> arrNames = new ArrayList<>();
[Link]("Pratham");
[Link]("Rahul"); ……
This makes a list to hold names like “Pratham”, “Rahul”, etc.
[Link] up the adapter
ArrayAdapter<String> adaptor = new ArrayAdapter<>(this,
[Link].simple_list_item_1, arrNames);
Think of the adapter as a “middleman” that takes the list of names (arrNames) and use
TextView(simple_list_item_1) and make an Entry in the ListView .
[Link](adaptor); //show the data.
[Link](new [Link]() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(position==0)
{
[Link]([Link],"Clicked First
item",Toast.LENGTH_LONG).show();
}
}
});
Logic for click , when click on any position.
Spinner(DropDown Menu) and Autocomplete(search Bar) view
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select ID Proof"
android:textSize="25sp"
android:textStyle="bold"
/>
<Spinner
android:id="@+id/spinner"
android:layout_width="165dp"
android:layout_height="wrap_content" />
</LinearLayout>
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:id="@+id/autoC"
android:hint="Search"
/>
[Link] (make adapter to it)
sp=findViewById([Link]);
ArrayAdapter<String> spinAdapter = new ArrayAdapter<>([Link],
[Link].simple_spinner_dropdown_item,arrids);
[Link](spinAdapter);
ac=findViewById([Link]);
ArrayAdapter<String> ad = new ArrayAdapter<>([Link],
[Link].simple_list_item_1,arrNames);
[Link](ad);
[Link](1); //tell after how many character suggestion should come
Themes (styles) app > res > [Link]
What are styles?
A style is a collection of XML attributes that define the look of a View or widget (like
Button, TextView, etc.).
Example: text size, color, padding, background.
<style name="MyButtonStyle">
<item name="android:background">#FF0000</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:padding">10dp</item>
</style>
Where can you apply it?
On a View →
android:theme or style attribute in XML:
<Button
style="@style/MyButtonStyle"
android:text="Click Me" />
Or on whole Layout as android:theme="@style/button"
2. What are themes?
A theme is a type of style that applies to the entire app or activity.
It controls overall UI look → like background color, status bar, action bar, text
appearances, etc.
Example (res/values/[Link] or [Link]):
<style name="MyAppTheme" parent="[Link]">
<item name="colorPrimary">#6200EE</item>
<item name="colorPrimaryVariant">#3700B3</item>
<item name="colorOnPrimary">#FFFFFF</item>
</style>
Where can you apply it?
In [Link] under <application> or <activity>:
<application
android:theme="@style/MyAppTheme">
</application>
Card view
What is CardView?
A container view with rounded corners, shadow, and elevation.
Useful for making cards like you see in Google apps (e.g., Play Store, News).
<[Link]
android:id="@+id/card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="12dp"
app:cardElevation="4dp"
app:cardUseCompatPadding="true">
<!-- Inside you can place any layout -->
</[Link]>
app:cardCornerRadius → corner radius (e.g., 12dp)
app:cardElevation → shadow depth (e.g., 4dp)
app:cardUseCompatPadding → adds padding inside for shadow space
Recycler View
RecyclerView is an advanced and flexible version of ListView.
It is used to display large sets of data efficiently by reusing views (hence, recycling
them).
Adapter
Connects the data source to the RecyclerView.
Creates and binds ViewHolders.
LayoutManager
Tells RecyclerView how to lay out the items.
Types:
o LinearLayoutManager (Vertical/Horizontal)
o GridLayoutManager
o StaggeredGridLayoutManager
Creating Recycle view:
<[Link]
android:id="@+id/recycle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
1. Make a layout : res -> layout -> right click -> new -> layout resource file (eg [Link])
In layout file : make template which will be used everytime , add layouts , texts , image , etc..
This will be used everytime by recycle .
2. [Link]
Custom layout for each contact item with:
o ImageView → Profile picture
o TextView → Name and Number
o Wrapped in CardView for a better UI.
📝 Why? → Defines how each row in the list will look visually.
[Link]
Now create a struct for layout using java class , why? -> if you have image and text in layout
, so you need to change them for different things , like contact , everyone has different info.
app > java > [Link] > right-click > java class > nameit (eg ContactModel).
package [Link];
public class ContactModel {
int img;
String name,number;
public ContactModel(int img , String name , String number)
{
[Link]=img;
[Link]=name;
[Link]=number;
}
}
4. [Link]
public class RecycleContactAdapter extends
[Link]<[Link]> {
Context context;
ArrayList<ContactModel> arrContact;
// Constructor to initialize context and contact list
RecycleContactAdapter(Context context, ArrayList<ContactModel>
arrContact) {
[Link] = context;
[Link] = arrContact;
}
// Inflate [Link] layout and return ViewHolder
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View v = [Link](context).inflate([Link],
parent, false);
return new ViewHolder(v); // ✅ Don't return null!
}
// Bind data (img, name, number) to each row
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position)
{
[Link]([Link](position).img);
[Link]([Link](position).name);
[Link]([Link](position).number);
}
// Return total number of items
@Override
public int getItemCount() {
return [Link]();
}
// ViewHolder class to hold row views
public class ViewHolder extends [Link] {
TextView txtName, txtNumber;
ImageView imgContact;
public ViewHolder(@NonNull View itemView) {
super(itemView);
txtName = [Link]([Link]);
txtNumber = [Link]([Link]);
imgContact = [Link]([Link]);
}
}
}
Why? → Adapter bridges the data (ContactModel) with the view ([Link]).
ViewHolder Class: Holds views to avoid findViewById calls repeatedly (performance).
onBindViewHolder: Binds image, name, and number to UI elements.
5. [Link]
Make RecyclerView obj then set a linear layout to it and start adding images(int) ,text(String)
RecyclerView rc = findViewById([Link]);
[Link](new LinearLayoutManager(this));
[Link](true); // Optional performance boost
ArrayList<ContactModel> arr = new ArrayList<>();
[Link](new ContactModel([Link].a, "A", "9734723873")); // Add contacts
RecycleContactAdapter adapter = new RecycleContactAdapter(this, arr);
[Link](adapter);
📝 Why? → Initializes RecyclerView and loads data using the adapter.
RecyclerView = List view for modern Android
Adapter = Connects data to RecyclerView
ViewHolder = Efficient item management
[Link] = How each row looks
ContactModel = Data structure
MainActivity = Where you bring it all together
Dynamic Dialog (popup) for Adding
1. Created the Dialog Layout (add_update_lay.xml) Purpose: This is a custom layout for the
input dialog.
Contains: A title TextView saying "Details"
Two input fields: EditText for Name and Contact Number
A Submit button in the center with rounded corners
Why: We need a separate layout file so that the dialog can have custom-designed inputs
instead of default system styles.
2. Created a Button in activity_main.xml to Trigger the Dialog
Button: A Button with id=btnOpenDialog (used to open the dialog).
Why: It acts as the trigger to display the popup when clicked.
[Link] Dialog Logic in [Link]
Setup Button to Show the Dialog
btnOpenDialog = findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
// Create and show the custom dialog
Dialog dialog = new Dialog([Link]);
[Link]([Link].add_update_lay);
Purpose: On button click, we are inflating and showing the custom-
designed dialog layout.
Get References to Dialog Inputs
EditText edtName = [Link]([Link].edit_name);
EditText edtNumber = [Link]([Link].edit_number);
Button btn = [Link]([Link].btn_submit);
Why: These fields let the user enter data that we will collect and add to the list.
Handle Submit Button Inside Dialog
[Link](new [Link]() {
@Override
public void onClick(View v) {
String name = "", number = "";
if (![Link]().toString().equals("")) {
name = [Link]().toString();
} else {
[Link]([Link], "Enter Valid Name",
Toast.LENGTH_SHORT).show();
return;
}
if (![Link]().toString().equals("") &&
[Link]().toString().length() == 10) {
number = [Link]().toString();
} else {
[Link]([Link], "Enter Valid Number",
Toast.LENGTH_SHORT).show();
return;
}
// Step 1: Add new contact to list
[Link](new ContactModel(name, number));
// Step 2: Notify adapter about the new item
[Link]([Link]() - 1);
// Step 3: Scroll to the new item
[Link]([Link]() - 1);
// Step 4: Close the dialog
[Link]();
}
});
[Link]();
}
});
🔁 UPDATE a Contact
How it Works:
When the user clicks on a contact ([Link]), it opens the
same custom dialog (add_update_lay.xml), but with:
o Title changed to "Update"
o Button text changed to "Update"
o Pre-filled values of the contact
On clicking Update:
o It replaces the existing item at position in the list with a new ContactModel
o Then calls notifyItemChanged(position) to refresh that item in the
RecyclerView
DELETE a Contact
🧠 How it Works:
When the user long presses a contact ([Link]), it shows a
confirmation dialog
If the user clicks "Yes": It removes the item from the list , Calls:
notifyItemRemoved(position) → Animates removal
notifyItemRangeChanged(position, [Link]()) → Adjusts the remaining items’
positions
Menu Items in Android
1. Purpose: Menu items are part of the action bar or overflow menu that offer actions
such as save, delete, share, etc.
2. XML File: Menus are created using an XML file inside the res/menu folder.
create a menu in res then create an menu resourse file
3.
<menu xmlns:android="[Link]
xmlns:app="[Link]
<item
android:id="@+id/opt_new"
android:title="New"
android:icon="@drawable/ic_new"
app:showAsAction="always" />
<!-- other items -->
</menu>
Inflating the Menu in java file:
You need to inflate the menu in the onCreateOptionsMenu method:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate([Link].menu_main, menu);
return true;
}
Handling Menu Item Clicks:
You handle item clicks in the onOptionsItemSelected method:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch ([Link]()) {
case [Link].opt_new:
// handle "new" action
return true;
case [Link].opt_open:
// handle "open" action
return true;
// add other cases as needed
default:
return [Link](item);
}
}
🔧 Designing Custom Views (like Buttons) with Drawable
Used to style UI components (like buttons, views) using shape, gradient, border, etc.
selector – For State-Based Styling
You want the view's appearance to change based on state,
<selector>
<item>
<shape>
<!-- Styling here -->
</shape>
</item>
</selector>
Element Purpose
<shape> Defines the shape (rectangle, oval, etc.)
android:shape Shape type (e.g., rectangle)
<solid> Background fill color
<stroke> Border color and width (optional)
Element Purpose
<corners> Rounded corners (e.g., android:radius="4dp")
<size> Width & height of the view
Save this file (e.g., custom_button.xml) in res/drawable/ and apply to a button like:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_button"
android:text="Click Me"/>
layer-list – For Layered Backgrounds
You want to stack multiple drawable layers (e.g., background + border + shadow).
Create Custom Toast
Create a layout : res/layout/custom_toast_layout.xml
<LinearLayout
android:background="@drawable/custom_toast_bg" //Custom Background
android:padding="12dp"
android:orientation="horizontal">
<ImageView set icon for toast
/>
<TextView set text for toast
/
</LinearLayout>
Show using java
LayoutInflater inflater = getLayoutInflater();
View view = [Link]([Link].custom_toast_layout, null);
TextView txtmsg = [Link]([Link]);
[Link]("Saved!");
Toast toast = new Toast(getApplicationContext());
[Link](view);
[Link](Toast.LENGTH_LONG);
[Link]([Link] | Gravity.CENTER_HORIZONTAL, 0, 50);
[Link]();
AlertDialog :
✅ 1. Basic Setup
[Link] builder = new [Link](context);
[Link]("Title");
[Link]("Your message here");
[Link]([Link]);
✅ 2. Add Buttons
[Link]("Yes", new [Link]() {
public void onClick(DialogInterface dialog, int which) {
// YES button action
}
});
[Link]("No", null); // No action
[Link]("Cancel", (dialog, which) -> {
// CANCEL action
});
[Link](); //SHOW THE DIALOG
✅ Notification Notes (Android Java)
1. Get Bitmap from Drawable (for Large Icon) means for message icon
Drawable drawable = [Link](getResources(),
[Link].green_check, null);
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap largeicon = [Link]();
Why: Needed for setLargeIcon() to show a custom image in the notification.
2. Get Notification Manager
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
→ Why: To manage and show the notification
3. Create Channel means news, update , message notification which can be turned off
String CHANNEL_ID = "my_channel_id";
if ([Link].SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Channel Name",
NotificationManager.IMPORTANCE_HIGH
);
[Link](channel);
}
Why: From Android 8.0 (API 26), channels are mandatory to show notifications.
4. Build Notification (full notification for any api version)
[Link] notification;
if ([Link].SDK_INT >= Build.VERSION_CODES.O) {
notification = new [Link](this)
.setLargeIcon(largeicon)
.setSmallIcon([Link])
.setContentTitle("New Message")
.setContentText("Hello, How are You?")
.setChannelId(CHANNEL_ID);
} else {
notification = new [Link](this)
.setLargeIcon(largeicon)
.setSmallIcon([Link])
.setContentTitle("New Message")
.setContentText("Hello, How are You?");
}
→ Why: Use .setChannelId() only for Android 8+, rest is same for all.
5. Show Notification
[Link](100, [Link]());
Why: Actually displays the notification. 100 is a unique ID (can be used to update/cancel
later). Any notification with same id will get merge as we have in whatsapp messages.
Advanced Notification Notes
1. PendingIntent
Intent iNotify = new Intent(this, [Link]);
[Link](Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = [Link](this, 100, iNotify,
PendingIntent.FLAG_UPDATE_CURRENT);
→ Why: Launches the app when user taps the notification. PendingIntent wraps the Intent
and allows the system to launch it later.
2. BigPictureStyle
[Link] bigPictureStyle = new
[Link]()
.bigPicture(largeicon)
.bigLargeIcon(largeicon)
.setBigContentTitle("Image sent by User")
.setSummaryText("Image message");
→ Why: Shows a large image inside the notification. Good for image-based messages (like
WhatsApp or Instagram notifications).
3. InboxStyle
[Link] inboxstyle = new [Link]()
.addLine("A")
.addLine("B")
.addLine("C")
...
.setBigContentTitle("Full Message")
.setSummaryText("Message came from user");
→ Why: Displays multiple lines of text in the notification. Useful for showing chats, emails,
or list-type data.
4. setOngoing(true)
→ Why: Makes the notification non-dismissible (like downloading or music playback). The
user cannot swipe it away unless handled manually.
Types of Intents in Android
1. Explicit Intent
Directly starts a specific activity or component within your app.
Intent i = new Intent([Link], [Link]);
startActivity(i);
2. Implicit Intent
Asks other apps to perform an action (like dial, SMS, email, share).
No target activity specified; system picks suitable app.
Using Button with Intents
1. Get button from layout:
Button btn = findViewById([Link]);
2. Set click listener:
3. [Link](new [Link]() {
@Override
public void onClick(View v) {
// Intent code here
}
});
📞 1. Dial a Phone Number (Implicit Intent)
Intent iDial = new Intent(Intent.ACTION_DIAL);
[Link]([Link]("[Link]
startActivity(iDial);
Opens dialer with number filled , No call is made automatically.
💬 2. Send SMS (Implicit Intent)
Intent iMsg = new Intent(Intent.ACTION_SENDTO);
[Link]([Link]("smsto:" + [Link]("+911234567890")));
[Link]("sms_body", "Hello");
startActivity(iMsg);
Opens messaging app with number and message pre-filled.
📧 3. Send Email (Implicit Intent)
Intent iEmail = new Intent(Intent.ACTION_SEND);
[Link]("message/rfc822");
[Link](Intent.EXTRA_EMAIL, new String[]{"abc@[Link]"});
[Link](Intent.EXTRA_SUBJECT, "Subject");
[Link](Intent.EXTRA_TEXT, "Body text");
startActivity([Link](iEmail, "Email via"));
Opens Gmail or any email app with details filled.
📤 4. Share Text (Implicit Intent)
Intent iShare = new Intent(Intent.ACTION_SEND);
[Link]("text/plain");
[Link](Intent.EXTRA_TEXT, "Download this app!");
startActivity([Link](iShare, "Share via"));
Lets user share text through any app (WhatsApp, Gmail, etc.).
[Link]() lets user pick the app (recommended) , Use [Link]() for phone
numbers, messages, links, etc.
🔹 What are Static Fragments?
Fragments added directly in the XML layout using the <fragment> tag.
They are loaded at app start and do not require Java/Kotlin code to attach them.
🧩 MainActivity Layout (activity_main.xml)
<fragment
android:id="@+id/Frag1"
android:name="[Link]"
... />
✅ Explanation:
Using <fragment> tag to add fragments statically.
android:name = fully qualified class name of the Fragment.
layout_weight is used to divide space between fragments vertically.
🧩 [Link]
Create Fragment : Right click on folder of [Link] , then create Blank Fragment
public class AFragment extends Fragment {
public AFragment() { } // Empty constructor (required)
@Override
public View onCreateView(...) {
View view = [Link]([Link].fragment_a, container, false);
TextView txtFrag = [Link]([Link]);
return view;
}
}
✅ Explanation:
onCreateView() inflates the fragment's UI.
[Link](...) loads fragment_a.xml. Required To Use Fragment component’s.
txtFrag refers to a TextView in that layout (you can modify or use it).
🔹 What are Dynamic Fragments?
Fragments that are added/removed/switched using Java/Kotlin code at runtime.
You use FragmentManager and FragmentTransaction.
<LinearLayout ...>
<!-- Buttons to switch Fragments -->
<AppCompatButton android:id="@+id/btnFragA" ... />
<AppCompatButton android:id="@+id/btnFragB" ... />
<AppCompatButton android:id="@+id/btnFragC" ... />
<!-- Placeholder to load fragments -->
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
✅ Explanation:
3 Buttons are used to trigger different Fragments.
FrameLayout is a fragment container where fragments will be loaded dynamically.
🧠 How to add Fragment Dynamically (Java Code in MainActivity)
[Link](v -> {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
[Link]([Link], new AFragment());
[Link]();
});
1. Get FragmentManager → getSupportFragmentManager()
2. Begin Transaction → beginTransaction()
3. Replace container → replace([Link], Fragment)
4. Commit changes → commit()
🔁 Repeat similar code for btnFragB and btnFragC with BFragment, CFragment.
Tabs Creation
To create a tabbed interface with three tabs: Chats , Status , Calls
[Link]
TabLayout tab = findViewById([Link]);
ViewPager viewPager = findViewById([Link]);
👉 Link XML views (TabLayout and ViewPager) to Java.
ViewPagerMessengerAdapter adapter = new
ViewPagerMessengerAdapter(getSupportFragmentManager());
👉 Create an adapter that tells ViewPager which fragment to load for each tab.
[Link](adapter);
[Link](viewPager);
👉 Connect the adapter to ViewPager and sync tabs with the pages.
🧩 [Link] Explained
Extends FragmentPagerAdapter — which helps ViewPager decide:
What fragment to show for each tab
What title to show on the tab
public Fragment getItem(int position) {
if(position==0)
{
return new chatFragment();
}
else if(position==1){
return new StatusFragment();
}
else {
return new CallsFragment();
}
}
👉 Called by ViewPager to get the Fragment for the tab at position.
public CharSequence getPageTitle(int position)
👉 Returns the title of each tab ("Chats", "Status", "Calls").
public int getCount() {
return 3;
}
👉 Total number of tabs/fragments = 3
Bottom Layout
1. Create Fragments (e.g., Home, Search, Profile)
2. Update XML Layout (activity_main.xml)
Relative Layout
<RelativeLayout xmlns:android="[Link]
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent">
Fragment Container
<FrameLayout
android:id="@+id/gcontainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bnView" />
BottomNavigationView
<[Link]
android:id="@+id/bnView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="@menu/nav_items" />
3. Set up BottomNavigationView in [Link]
BottomNavigationView bnView = findViewById([Link]);
FrameLayout gcontainer = findViewById([Link]);
Step 2: Set Fragment on Item Selected
[Link](new
[Link]() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch ([Link]()) {
case [Link].nav_home:
selectedFragment = new HomeFragment();
break;
case [Link].nav_search:
selectedFragment = new SearchFragment();
break;
case [Link].nav_profile:
selectedFragment = new ProfileFragment();
break;
}
loadFragment(selectedFragment);
return true;
}
});
Load Fragment in FrameLayout
public void loadFragment(Fragment fragment) {
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
[Link]([Link], fragment);
[Link]();
}
set Default Fragment(optional) in oncreate()
[Link]([Link].nav_home); // Set default item
4. Handle Edge-to-Edge (System Insets)
In onCreate() Method: if bottomLayout Appears Elivated from bottom
[Link](findViewById([Link]), (v,
insets) -> {
Insets systemBars = [Link]([Link]());
[Link]([Link](), [Link](),
[Link](), [Link]);
return insets;
});
Enable Edge-to-Edge at the start of onCreate():
[Link](this);
5. Add Menu Items (menu/nav_items.xml)
icon which will come on Bottom
<menu xmlns:android="[Link]
<item
android:id="@+id/nav_home"
android:icon="@drawable/ic_home"
android:title="Home" />
...
...
</menu>
1. Add Drawer Layout in activity_main.xml
DrawerLayout wraps the content and navigation.
Inside it, we have the AppBarLayout (with the Toolbar) and the
NavigationView (the drawer itself).
<?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:id="@+id/main_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<include layout="@layout/app_bar" //Toolbar and Main Content
includes
/>
<!-- Navigation Drawer -->
<[Link]
android:id="@+id/navigationView"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/header_lay"
app:menu="@menu/nav_items"
/>
</[Link]>
2. Set up MainActivity ([Link])
Declare Toolbar and DrawerLayout variables.
Initialize them inside onCreate() after setContentView().
Set up a Toolbar with setSupportActionBar() and Drawer Toggle.
public class MainActivity extends AppCompatActivity {
NavigationView navigationView;
DrawerLayout drawerLayout;
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// Initialize views after content view is set
drawerLayout = findViewById([Link].drawer_layout);
toolbar = findViewById([Link]);
navigationView = findViewById([Link].navigation_view);
setSupportActionBar(toolbar); // Set Toolbar as ActionBar
// Toggle Drawer when Toolbar icon is clicked
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, [Link],
[Link]);
[Link](toggle);
[Link]();
}
}
3. Add ActionBarDrawerToggle for Drawer Toggle
ActionBarDrawerToggle manages the opening and closing of the drawer
when the toolbar icon is clicked.
It automatically syncs with the Hamburger icon and handles transitions.
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, [Link],
[Link]);
[Link](toggle);
[Link]();
4. Add Menu Items in menu/nav_items.xml
Define the menu items in NavigationView.
<menu xmlns:android="[Link]
<item android:id="@+id/nav_home"
android:title="Home"/>
<item android:id="@+id/nav_settings"
android:title="Settings"/>
</menu>
5. Create Header Layout for Navigation Drawer (optional)
Define a header layout for your drawer.
<LinearLayout
xmlns:android="[Link]
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:src="@drawable/header_image"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome User"/>
</LinearLayout>
6. Handle Navigation Item Selection (optional)
Add logic to handle menu item selection in the Drawer.
[Link](item -> {
int id = [Link]();
if (id == [Link].nav_home) {
// Handle Home item
} else if (id == [Link].nav_settings) {
// Handle Settings item
}
[Link]([Link]); // Close the drawer
return true;
});
✅ Passing Data from Activity to Fragment — Summary Notes
🔹 1. Create a static getInstance() method in Fragment
Used to create the Fragment and pass data using a Bundle.
public static ProfileFragment getInstance(String val1, int val2) {
ProfileFragment profileFragment = new ProfileFragment();
Bundle bundle = new Bundle();
[Link]("arg1", val1);
[Link]("arg2", val2);
[Link](bundle);
return profileFragment;
}
🔹 2. Receive data in onCreateView() of Fragment
Extract arguments using getArguments().
if(getArguments()!=null)
{
String name = getArguments().getString(ARG1,"Raman");
int rollNp = getArguments().getInt(ARG2);
( (MainActivity) requireActivity()).CallFromFragment(); //Call
any function from Activity
Log.d("Value from act","Name :"+name+" And RollNO :"+rollNp);
}
((MainActivity) requireActivity()).CallFromFragment();
This line calls a public method from the hosting
MainActivity.
requireActivity() gives you the activity instance, which
you cast to MainActivity.
🔹 3. Call getInstance() from Activity while loading Fragment
Replace or add fragment using FragmentTransaction.
loadFreg([Link]("Ramanujan", 11), 0);
✅ What You Achieved:
Created a reusable method to pass data to a fragment.
Used Bundle to safely pass data.
Received and used data inside the fragment.
Clean and modular communication from Activity → Fragment.
📘 [Fragment Navigation] – How to Clear Entire Back Stack in Android
Problem: When navigating back to the root (e.g., ProfileFragment), we want to
clear all previous fragments from the stack so that pressing back exits the app
instead of going back to previous fragments.
✅ Reliable Way to Clear Fragment Back Stack
public void loadFreg(Fragment fragment, int flag) {
FragmentManager fm = getSupportFragmentManager();
// Clear the entire back stack before loading ProfileFragment
if (flag == 0) {
while ([Link]() > 0) {
[Link]();
}
}
FragmentTransaction ft = [Link]();
[Link]([Link], fragment);
if (flag == 0) {
// Mark this as the new root
[Link]("ROOT");
} else {
[Link](null); // Normal flow
}
[Link]();
}
Use this logic before loading the root fragment:
FragmentManager fm = getSupportFragmentManager();
while ([Link]() > 0) {
[Link]();
}
Then load your fragment:
[Link]()
.replace([Link], new ProfileFragment())
.commit();
Fetch data from API
Step What
1️⃣ Add Retrofit & Gson dependencies
2️⃣ Create data model (User)
3️⃣ Define API interface
4️⃣ Build Retrofit instance
5️⃣ Call API & handle response
Steps to Add WebView in Android App
1. Add Internet Permission
In your [Link], add the following permission to allow
the app to access the internet.
<uses-permission android:name="[Link]"/>
2. Modify Layout to Include WebView
In your XML layout file (activity_main.xml or fragment_status.xml), add
the WebView element:
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3. Initialize WebView in Activity/Fragment
In your Activity or Fragment, reference the WebView and enable
necessary settings:
WebView webView = findViewById([Link]);
[Link]().setJavaScriptEnabled(true); // Enable JavaScript
for dynamic content
4. Load URL in WebView
Use loadUrl() to load a website into the WebView.
[Link]("[Link]
5. Handle URL Loading Inside WebView
To prevent external browsers from opening, set a WebViewClient:
[Link](new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view,
WebResourceRequest request) {
[Link]([Link]().toString()); // Stay within
WebView
return true;
}
});
Save login state using SharedPreferences
🧠 What is SharedPreferences?
It's used to store small key-value data locally, like:
o Login state (true / false)
o User preferences (theme, settings, etc.)
It remains stored even after app is closed/restarted.
Splash Screen – decides where to go (LoginScreen or MainActivity)
LoginScreen – sets login flag true when login button clicked
MainActivity – resets flag to false on logout
[Link] (inside onCreate())
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
SharedPreferences pref = getSharedPreferences("login",
MODE_PRIVATE);
boolean check = [Link]("flag", false);
Intent iNext;
if (check) {
iNext = new Intent([Link], [Link]);
} else {
iNext = new Intent([Link], [Link]);
}
startActivity(iNext);
finish(); // Close the SplashActivity
}
}, 3000);
2. [Link]
btnLogin = findViewById([Link]);
[Link](v -> {
SharedPreferences pref = getSharedPreferences("login", MODE_PRIVATE);
[Link] editor = [Link]();
[Link]("flag", true); // Save login as true
[Link]();
Intent iHome = new Intent([Link], [Link]);
startActivity(iHome);
finish(); // Optional: close login screen
});
3. [Link] (Logout part)
btnlogout = findViewById([Link]);
[Link](v -> {
SharedPreferences pref = getSharedPreferences("login", MODE_PRIVATE);
[Link] editor = [Link]();
[Link]("flag", false); // Log out
[Link]();
Intent iBack = new Intent([Link], [Link]);
startActivity(iBack);
finish(); // Close main activity
});
When logout button is clicked:
It sets "flag" to false.
Redirects to login screen.
📘 SQLite Basic Operations (Android) – Notes
1. Create SQLite Helper Class
Extend SQLiteOpenHelper to manage DB.
public class MyDBhelper extends SQLiteOpenHelper {
// Define DB name, version, table name & columns
}
🧱 2. Create Table (in onCreate)
[Link]("CREATE TABLE contacts(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT, phone_no TEXT)");
🔁 3. Upgrade Table (in onUpgrade)
[Link]("DROP TABLE IF EXISTS contacts");
onCreate(db);
🔨 CRUD Operations
➕ Add Contact
ContentValues values = new ContentValues();
[Link]("name", name);
[Link]("phone_no", phone);
[Link]("contacts", null, values);
📥 Fetch All Contacts
Cursor cursor = [Link]("SELECT * FROM contacts", null);
while([Link]()) {
// create ContactModel & add to ArrayList
}
✏️Update Contact
ContentValues cv = new ContentValues();
[Link]("phone_no", newNumber);
[Link]("contacts", cv, "id = ?", new String[]{[Link](id)});
❌ Delete Contact
[Link]("contacts", "id = ?", new String[]{[Link](id)});
🧠 ContactModel Class
public class ContactModel {
int id;
String name,phone_no;
🔧 Usage in MainActivity
MyDBhelper db = new MyDBhelper(this);
[Link]("Raman", "94872...");
[Link](2);