![]() |
A Fragment is a piece of an activity that enables 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. In this article, we are going to implement an application in which we can get the coordinates of our current location. We will see that who we can get that current location in Fragment. What we are going to build in this article?Here is a sample video of what we are going to build in this article. Note that we are going to implement this project using Java language. Step by Step ImplementationStep 1. Create a New Project
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? Step 2. Adding required dependency Navigate to Gradle Scripts > gradle.scripts(module) and add the following dependency to it implementation 'com.google.android.gms:play-services-location:17.0.0' Step 3. Adding required permissions Navigate to the AndroidManifest.xml file and add the following piece of code to it- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> Step 4. Working on XML files Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML
Navigate to app > right-click > new > fragment > blank fragment and name it as MainFragment. Use the following code in fargment_main.xml file- XML
Step 5. Working on Java files Navigate to the MainActivity.java file and use the following code in it. Comments are added to the code to have a better understanding. Java
Navigate to the MainFragment.java file and use the following code in it. Comments are added to the code to have a better understanding. Java
Here is the final output of our application. Output: |
Reffered: https://www.geeksforgeeks.org
Android |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |