Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 36

FRAGMENTS IN ANDROID

Build a Simple Flashlight in android: Code


Colors.xml file
Mainactivity.xml
Important terms in xml code
• LinearLayout: It is a view group that aligns the contained views either horizontally or
vertically. In this case, it's set to align its contents vertically (android:orientation="vertical").
It's the root layout container for the activity's UI elements.
• TextView: It's a UI element used to display text to the user. In this code, it displays the text
"Flashlight". Various attributes like android:textColor, android:textSize, and
android:textStyle are used to customize its appearance.
• View: This is a simple view used as a divider between the TextView and the ToggleButton.
It's given a height of 1dp and a background color of darker gray.
• ToggleButton: It's a UI element used to toggle between two states, typically ON and OFF. In
this code, it's used to control the flashlight, with the ID toggle_flashlight. When clicked, it
calls the toggleFlashLight() method defined in the associated activity. Various attributes like
android:layout_width, android:layout_height, and android:textSize are used to set its size
and appearance.
ToggleButton
• The ToggleButton is a specialized button that has two states: pressed
and not pressed. It represents a boolean value (true/false) where it
can be toggled between two states by the user. When clicked, it
changes its state from one to the other.
Important Properties:
• android:id: Specifies a unique identifier for the ToggleButton.
• android:layout_width and android:layout_height: Defines the width
and height of the ToggleButton.
• android:layout_gravity: Specifies how the ToggleButton should be
positioned within its parent layout.
• android:onClick: Specifies the name of the method to call when the
ToggleButton is clicked. This method must be defined in the activity or
fragment associated with the layout.
Important Properties:
• android:text: Sets the text displayed on the ToggleButton.
• android:textSize: Sets the size of the text displayed on the ToggleButton.
• android:checked: Sets the initial state of the ToggleButton. If set to "true", the
button will be initially in the pressed state.
• android:background: Defines the background drawable for the ToggleButton.
• android:button: Specifies the drawable used as the button indicator for the
ToggleButton. This drawable will change its state when the ToggleButton is
clicked.
• android:checkedButton: Sets the drawable used as the button indicator when
the ToggleButton is in the pressed state.
Mainactivity.java
// Import necessary packages and classes
package com.example.flashlight;

import androidx.appcompat.app.AppCompatActivity; // Import the AppCompatActivity class from


the androidx.appcompat library

import android.os.Bundle; // Import the Bundle class from the android.os package

import android.content.Context; // Import the Context class from the android.content package
import android.hardware.camera2.CameraAccessException; // Import the CameraAccessException
class from the android.hardware.camera2 package
import android.hardware.camera2.CameraManager; // Import the CameraManager class from the
android.hardware.camera2 package
Mainactivity.java
// Import necessary packages and classes
package com.example.flashlight;

import androidx.appcompat.app.AppCompatActivity; // Import the AppCompatActivity class from


the androidx.appcompat library

import android.os.Bundle; // Import the Bundle class from the android.os package

import android.content.Context; // Import the Context class from the android.content package
import android.hardware.camera2.CameraAccessException; // Import the CameraAccessException
class from the android.hardware.camera2 package
import android.hardware.camera2.CameraManager; // Import the CameraManager class from the
android.hardware.camera2 package
// Define the MainActivity class, which extends AppCompatActivity
public class MainActivity extends AppCompatActivity {

// Declare private variables for ToggleButton, CameraManager, and String to


store camera ID
private ToggleButton toggleFlashLightOnOff; // ToggleButton to control the
flashlight
private CameraManager cameraManager; // CameraManager to interact with
the device's camera
private String getCameraID; // String variable to store the ID of the device's
camera
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Register the ToggleButton with specific ID from the layout XML


toggleFlashLightOnOff = findViewById(R.id.toggle_flashlight);
// Initialize the cameraManager to interact with camera devices
cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

// Exception is handled, because we need to check whether


// the camera resource is being used by another
// service or not.
try {
// O means back camera unit,
// 1 means front camera unit
getCameraID = cameraManager.getCameraIdList()[0]; // Get the ID of the first camera device
} catch (CameraAccessException e) {
e.printStackTrace(); // Print the stack trace if an error occurs accessing the camera
}
}
// This method toggles the flashlight on or off when the ToggleButton is clicked.
// It requires API level 23 or higher because older devices may not have a flashlight feature.
@RequiresApi(api = Build.VERSION_CODES.M)
public void toggleFlashLight(View view) {
// Check if the ToggleButton is checked (i.e., the flashlight is turned on)
if (toggleFlashLightOnOff.isChecked()) {
// Exception is handled to check whether the camera resource is being used by
another service or not.
try {
// Set the torch mode to ON
cameraManager.setTorchMode(getCameraID, true);
// Show a Toast message to inform the user that the flashlight is turned ON
Toast.makeText(MainActivity.this, "Flashlight is turned ON", Toast.LENGTH_SHORT).show();
} catch (CameraAccessException e) {
// Print the stack trace if an error occurs accessing the camera
e.printStackTrace();
}
} else {
// Exception is handled to check whether the camera resource is being used by another
service or not.
try {
// Set the torch mode to OFF
cameraManager.setTorchMode(getCameraID, false);
// Show a Toast message to inform the user that the flashlight is turned OFF
Toast.makeText(MainActivity.this, "Flashlight is turned OFF",
Toast.LENGTH_SHORT).show();
} catch (CameraAccessException e) {
// Print the stack trace if an error occurs accessing the camera
e.printStackTrace();
}
}
}
Important Methods
• Package: A package is a namespace that organizes a set of related classes and interfaces. In
this code, com.example.flashlight is the package name where the MainActivity class is
located.
• AppCompatActivity: AppCompatActivity is a class provided by the Android Jetpack library
that serves as a base class for activities in Android apps. It provides compatibility support
for newer features on older versions of Android.
• Bundle: A Bundle is a collection of key-value pairs, where the keys are always strings. It's
generally used for passing data between various Android components. In the onCreate
method, the savedInstanceState parameter is a Bundle that provides data about the
previous state of the activity.
• Context: Context is an Android class that provides access to application-specific resources
and classes, as well as calls for application-level operations such as launching activities,
broadcasting intents, etc. In this code, Context.CAMERA_SERVICE is used to access the
camera service.
Important Methods
• CameraManager: CameraManager is a class introduced in Android API level 21 (Lollipop) that
provides access to camera devices available on the Android device. It allows applications to
query for available cameras and control camera features, such as turning the flashlight on and
off.
• ToggleButton: ToggleButton is a UI element in Android that represents a two-state button. It
can be either checked (on) or unchecked (off). In this code, it's used to control the state of the
flashlight (on/off).
• Toast: Toast is a notification message that pops up on the screen for a short duration. It's often
used to display feedback to the user. In this code, it's used to inform the user about the status
of the flashlight (turned on/off).
• RequiresApi: RequiresApi is an annotation that specifies that the method or class is only
available on devices running a specific version of Android. In this code, it's used to ensure that
the toggleFlashLight method and the finish method are only called on devices running API
level 23 (Marshmallow) or higher, where the flashlight feature is available.
Important Methods
• e.printStackTrace() is called when a CameraAccessException occurs. It
prints detailed information about the exception, including the class
name, message, and stack trace, to the standard error stream. This
information can be helpful for developers to identify and troubleshoot
issues related to camera access.
What is printStackTrace()

• The printStackTrace() method is a built-in method in Java that belongs


to the Throwable class. It prints the stack trace of an exception to the
standard error stream. This method is often used for debugging
purposes to diagnose and trace the cause of an exception.
Throwable Class
• The Throwable class is a fundamental class in Java's exception
handling mechanism. It serves as the superclass for all errors and
exceptions that can be thrown during the execution of a Java
program.
The Throwable class provides several
methods to work with exceptions,
including:
• getMessage(): Returns a detailed message string describing the cause of the
exception.
• printStackTrace(): Prints the stack trace of the exception to the standard error
stream (usually the console), including the class name, method name, and line
number where the exception occurred.
• getCause(): Returns the cause of the exception, which is another Throwable object
or null if the cause is nonexistent or unknown.
• toString(): Returns a short description of the exception, usually containing the class
name and the result of calling getMessage().
• getStackTrace(): Returns an array of StackTraceElement objects representing the
stack trace of the exception
Fragments & Adapters
Content
• Fragments & Adapters
• Intro to Fragments in Android
• Fragment Lifecycle in Android
• How to Create a New Fragment in Android Studio?
• How to Create Swipe Navigation in Android?
• ViewPager Using Fragments in Android with Example
• Fragment is a piece of an activity that enables a more modular
activity design. A fragment encapsulates functionality so that it is
easier to reuse within activities and layouts. Android devices exist in a
variety of screen sizes and densities.
• Fragments simplify the reuse of components in different layouts and
their logic. You can build single-pane layouts for handsets (phones)
and multi-pane layouts for tablets. You can also use fragments also to
support different layouts for landscape and portrait orientation on a
smartphone. The below image shows how two UI modules defined by
fragments can be combined into one activity for a tablet design but
separated for a handset design.
Fragment Life Cycle
• Android fragments have their own life cycle very similar to an android
activity.
• onAttach() : The fragment instance is associated with an activity
instance. The fragment and the activity is not fully initialized. Typically
you get in this method a reference to the activity which uses the
fragment for further initialization work.
• onCreate() : The system calls this method when creating the
fragment. You should initialize essential components of the fragment
that you want to retain when the fragment is paused or stopped, then
resumed.
• onCreateView() : The system calls this callback when it’s time for the
fragment to draw its user interface for the first time. To draw a UI for
your fragment, you must return a View component from this method
that is the root of your fragment’s layout. You can return null if the
fragment does not provide a UI.
• onActivityCreated() : The onActivityCreated() is called after the
onCreateView() method when the host activity is created. Activity and
fragment instance have been created as well as the view hierarchy of
the activity. At this point, view can be accessed with the
findViewById() method. example. In this method you can instantiate
objects which require a Context object
• onStart() : The onStart() method is called once the fragment gets
visible.
• onResume() : Fragment becomes active.
• onPause() : The system calls this method as the first indication that the
user is leaving the fragment. This is usually where you should commit
any changes that should be persisted beyond the current user session.
• onStop() : Fragment going to be stopped by calling onStop()
• onDestroyView() : Fragment view will destroy after call this method
• onDestroy() :called to do final clean up of the fragment’s state but Not
guaranteed to be called by the Android platform.
Types of Fragments
• Single frame fragments : Single frame fragments are using for hand
hold devices like mobiles, here we can show only one fragment as a
view.
• List fragments : fragments having special list view is called as list
fragment
• Fragments transaction : Using with fragment transaction. we can
move one fragment to another fragment.
Handling the Fragment Lifecycle
• A Fragment exist in three states:
• Resumed : The fragment is visible in the running activity.
• Paused : Another activity is in the foreground and has focus, but the
activity in which this fragment lives is still visible (the foreground
activity is partially transparent or doesn’t cover the entire screen).
• Stopped : The fragment is not visible. Either the host activity has been
stopped or the fragment has been removed from the activity but
added to the back stack. A stopped fragment is still alive (all state and
member information is retained by the system). However, it is no
longer visible to the user and will be killed if the activity is killed.
Defining and using fragments
• To define a new fragment we
either extend
the android.app.Fragment cl
ass or one of its subclasses.
import android.app.Fragment; @Override
import android.os.Bundle; public View onCreateView(LayoutInflater inflater, ViewGroup
container,Bundle savedInstanceState){
import android.view.LayoutInflater; View view =
inflater.inflate(R.layout.fragment_rssitem_detail,container, false);
import android.view.View;
import android.view.ViewGroup; return view;
}
import android.widget.TextView; public void setText(String text){
TextView view = (TextView)
public class DetailFragment extends getView().findViewById(R.id.detailsText);
Fragment { view.setText(text);
}
}
Fragment Transaction:
• While for an dynamic activity we are
set buttons for an interactive UI. If we
are set after clicking the button the
fragment should appear then we have
to get help from Fragment Manager. It
handle all the fragment in an activity.
We need to set fragment transaction
with the help of fragment manager
and and begin transaction, and then
simply replace the layout of the
fragment with desired place.

You might also like