diff --git a/an_aws.json b/an_aws.json new file mode 100644 index 0000000000000000000000000000000000000000..17f9794142870eaea7c147917e47eae9f1e0a5b4 --- /dev/null +++ b/an_aws.json @@ -0,0 +1 @@ +[{"text": "\nAndroid Menus\n\nIn android, Menu is an important part of the UI component which is used to provide some common functionality around the application. With the help of menu, users can experience a smooth and consistent experience throughout the application. In order to use menu, we should define it in a separate XML file and use that file in our application based on our requirements. Also, we can use menu APIs to represent user actions and other options in our android application activities.\nHow to define Menu in XML File?\nAndroid Studio provides a standard XML format for the type of menus to define menu items. We can simply define the menu and all its items in XML menu resource instead of building the menu in the code and also load menu resource as menu object in the activity or fragment used in our android application. Here, we should create a new folder menu inside of our project directory (res/menu) to define the menu and also add a new XML file to build the menu with the following elements. Below is the example of defining a menu in the XML file (menu_example.xml).\nWay to create menu directory and menu resource file:\nTo create the menu directory just right-click on res folder and navigate to res->New->Android Resource Directory. Give resource directory name as menu and resource type also menu. one directory will be created under res folder.\nTo create xml resource file simply right-click on menu folder and navigate to New->Menu Resource File. Give name of file as menu_example. One menu_example.xml file will be created under menu folder.XML \n\n\n\n\n It is the root element that helps in defining Menu in XML file and it also holds multiple elements.\n It is used to create a single item in the menu. It also contains nested element in order to create a submenu.\n It is optional and invisible for elements to categorize the menu items so they can share properties like active state, and visibility.activity_main.xml\nIf we want to add a submenu in menu item, then we need to add a element as the child of an . Below is the example of defining a submenu in a menu item.XML \n\n\n\n\n\n\n\n\nAndroid Different Types of Menus\nIn android, we have three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are the following:Android Options Menu\nAndroid Context Menu\nAndroid Popup MenuAndroid Options Menu is a primary collection of menu items in an android application and is useful for actions that have a global impact on the searching application. Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and is useful for elements that affect the selected content or context frame. Android Popup Menu displays a list of items in a vertical list which presents the view that invoked the menu and is useful to provide an overflow of actions related to specific content."}, {"text": "\nHow to add a Pie Chart into an Android Application\n\nA Pie Chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses \u201cpie slices\u201d, where each sector shows the relative sizes of data. A circular chart cuts in the form of radii into segments describing relative frequencies or magnitude also known as a circle graph. A pie chart represents numbers in percentages, and the total sum of all segments needs to equal 100%. \nHere is the Final Application which will be created.\nhttps://media.geeksforgeeks.org/wp-content/uploads/20240521115249/Pie-Chart-Android-Java.mp4\nStep-by-Step Implementation of Pie Chart in Android ApplicationSo let\u2019s see the steps to add a Pie Chart into an Android app. \nStep 1: Opening/Creating a New ProjectTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. \nNote: SelectJavaas the programming language.\nBy default, there will be two files activity_main.xml and MainActivity.java.\nStep 2: Before going to the Coding Section first you have to do some Pre-Task. 1. Navigate to Gradle Scripts->build.gradle (Module: app) Add the dependencies mentioned below:dependencies{ // For Card view implementation 'androidx.cardview:cardview:1.0.0' // Chart and graph library implementation 'com.github.blackfizz:eazegraph:1.2.2@aar' implementation 'com.nineoldandroids:library:2.4.0'}After Importing following dependencies and click the \u201csync Now\u201d on the above pop up. \n2. Naviagate to app->res->values->colors.xml: Add and Set the colors for your app. \ncolors.xml\n\n #024265\n #024265\n #05af9b #fb7268\n #ededf2\n #E3E0E0 #FFA726\n #66BB6A\n #EF5350\n #29B6F6Step 3: Designing the Layout of the ApplicationBelow is the code for the xml file. \nactivity_main.xml After using this code in .xml file, the Layout will be like:Step 4: Changes in the MainActivity File to Add Functionality in the Application Open the MainActivity.java file there within the class, first of all create the object of TextView class and the pie chart class. \nJava // Create the object of TextView and PieChart class\n TextView tvR, tvPython, tvCPP, tvJava;\n PieChart pieChart;Secondly inside onCreate() method, we have to link those objects with their respective id\u2019s that we have given in .XML file. \nJava // Link those objects with their respective\n // id's that we have given in .XML file\n tvR = findViewById(R.id.tvR);\n tvPython = findViewById(R.id.tvPython);\n tvCPP = findViewById(R.id.tvCPP);\n tvJava = findViewById(R.id.tvJava);\n pieChart = findViewById(R.id.piechart);Create a private void setData() method outside onCreate() method and define it.Inside setData() method the most important task is going to happen that is how we set the data in the text file and as well as on the piechart. First of all inside setData() method set the percentage of language used in their respective text view. \nJava // Set the percentage of language used\n tvR.setText(Integer.toString(40));\n tvPython.setText(Integer.toString(30));\n tvCPP.setText(Integer.toString(5));\n tvJava.setText(Integer.toString(25));And then set this data to the pie chart and also set their respective colors using addPieSlice() method. \nJava // Set the data and color to the pie chart\n pieChart.addPieSlice(new PieModel(\"R\",Integer.parseInt(tvR.getText().toString()),\n Color.parseColor(\"#FFA726\")));\n \n pieChart.addPieSlice(new PieModel(\"Python\",Integer.parseInt(tvPython.getText().toString()),\n Color.parseColor(\"#66BB6A\"))); pieChart.addPieSlice(new PieModel(\"C++\",Integer.parseInt(tvCPP.getText().toString()),\n Color.parseColor(\"#EF5350\"))); pieChart.addPieSlice(new PieModel(\"Java\",Integer.parseInt(tvJava.getText().toString()),\n Color.parseColor(\"#29B6F6\")));For better look animate the piechart using startAnimation(). \nJava // To animate the pie chart\n pieChart.startAnimation();At last invoke the setData() method inside onCreate() method. \nBelow is the complete code for MainActivity.java file: \nMainActivity.javapackage com.example.final_pie_chart_java;// Import the required libraries\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.graphics.Color;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport org.eazegraph.lib.charts.PieChart;\nimport org.eazegraph.lib.models.PieModel;public class MainActivity\n extends AppCompatActivity { // Create the object of TextView\n // and PieChart class\n TextView tvR, tvPython, tvCPP, tvJava;\n PieChart pieChart; @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main); // Link those objects with their\n // respective id's that\n // we have given in .XML file\n tvR = findViewById(R.id.tvR);\n tvPython = findViewById(R.id.tvPython);\n tvCPP = findViewById(R.id.tvCPP);\n tvJava = findViewById(R.id.tvJava);\n pieChart = findViewById(R.id.piechart); // Creating a method setData()\n // to set the text in text view and pie chart\n setData();\n } private void setData()\n { // Set the percentage of language used\n tvR.setText(Integer.toString(40));\n tvPython.setText(Integer.toString(30));\n tvCPP.setText(Integer.toString(5));\n tvJava.setText(Integer.toString(25)); // Set the data and color to the pie chart\n pieChart.addPieSlice(\n new PieModel(\n \"R\",\n Integer.parseInt(tvR.getText().toString()),\n Color.parseColor(\"#FFA726\")));\n pieChart.addPieSlice(\n new PieModel(\n \"Python\",\n Integer.parseInt(tvPython.getText().toString()),\n Color.parseColor(\"#66BB6A\")));\n pieChart.addPieSlice(\n new PieModel(\n \"C++\",\n Integer.parseInt(tvCPP.getText().toString()),\n Color.parseColor(\"#EF5350\")));\n pieChart.addPieSlice(\n new PieModel(\n \"Java\",\n Integer.parseInt(tvJava.getText().toString()),\n Color.parseColor(\"#29B6F6\"))); // To animate the pie chart\n pieChart.startAnimation();\n }\n}Output:Run The Application, Check this article Android | Running your first Android app as the reference.Note : To access the full android application using Pie chat check this repository: Pie Chart Android Application\nClick Here to Learn How to Create Android Application\n"}, {"text": "\nDesugaring in Android\n\nGoogle has officially announced Kotlin as a recommended language for Android Development and that\u2019s why so many developers are switching from Java to Kotlin for Android development. So day by day new APIs are been introduced in Android by the Google Team and which are available in newer versions of Android devices as well. So Desugaring is also one of the important features in Android that we should enable in our app which will allow our apps to work in lower API levels as well. So in this article, we will learn about Desugaring.What is Desugaring?\nWhy we need Desugaring?\nPractical Implementation of Desugaring.\nWhat\u2019s happening under the hood?What is Desugaring?\nAndroid devices are getting optimized day by day. So many features in Android for users as well as developers are getting optimized. When any operating system of Android is developed, it is delivered with so many Java classes which provides support to different apps in user\u2019s devices for various functionalities such as time, date, and many other features. Now if we consider time API it was introduced in API level 26 and the apps which use this API will crash on the lower API level devices such as Marshmallow and lower versions. So in this case to avoid the app crashes Desugaring comes into play. It allows lower API levels to work with new JAVA libraries.\nWhy We Need Desugaring?\nSuppose for example we are using a new time API which is introduced in API level 26 and we have used this API of time in our app. This app will work perfectly for API level 26 and above but when we will install this app on the lower API level let suppose API level 23 or lower than that then our app will crash because our device OS supports the features provided from API level 23 and we are using features of API level 26 which will not work. So for avoiding this app crashes and to support the new features from API level 26 into API level 23 we have to add Desugaring in our app.\nPractical Implementation of Desugaring in Android\nWhen we are using features provided by API level 26 in the devices lower than API level 26 then the app will crash. In the apps with a lower API level, we will get to see an error as NoClassDefFoundError. So to resolve this error we have to enable Desugaring in Android.\nStep by Step implementation of Desugaring\nStep 1: Navigate to the Gradle Scripts > build.gradle(:app) and inside your dependencies section add the dependency given belowcoreLibraryDesugaring \u2018com.android.tools:desugar_jdk_libs:1.0.9\u2019Now after adding this dependency you have to add the below line in your compileOptions part of your codecoreLibraryDesugaringEnabled trueStep 2: Now we have to enable multiDex in our app for that navigate to your Gradle file inside that in the section of defaultConfig section add the below line asmultiDexEnabled trueAnd sync your project. After the successful project sync, Desugaring has been implemented in our app and now we will not get to see NoClassDefFoundError in the devices with lower API levels. The complete code for the Gradle file is given below:Kotlin plugins { \nid 'com.android.application'\nid 'kotlin-android'\n} android { \ncompileSdkVersion 30\nbuildToolsVersion \"30.0.2\"defaultConfig { \napplicationId \"com.gtappdevelopers.desugaring\"\nminSdkVersion 19\nmultiDexEnabled true\ntargetSdkVersion 30\nversionCode 1\nversionName \"1.0\"testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n} buildTypes { \nrelease { \nminifyEnabled false\nproguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'\n} \n} \ncompileOptions { \nsourceCompatibility JavaVersion.VERSION_1_8 \ntargetCompatibility JavaVersion.VERSION_1_8 \ncoreLibraryDesugaringEnabled true\n} \nkotlinOptions { \njvmTarget = '1.8'\n} \n} dependencies { implementation \"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version\"\nimplementation 'androidx.core:core-ktx:1.3.2'\ncoreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'\nimplementation 'androidx.appcompat:appcompat:1.2.0'\nimplementation 'com.google.android.material:material:1.2.1'\nimplementation 'androidx.constraintlayout:constraintlayout:2.0.4'\ntestImplementation 'junit:junit:4.+'\nandroidTestImplementation 'androidx.test.ext:junit:1.1.2'\nandroidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'\n}What\u2019s Happening Under the Hood?\nSo what is happening here and how the java classes which were missing suddenly appear here. This is because of D8 and R8 tools. Previously for converting your app\u2019s code in dex code we have to use Proguard but to reduce compile-time and to reduce app size the new R8 tool was introduced. This R8 tool provides the support of missing Java classes. When this tool converts your app\u2019s code into dex code it also adds dex code of new java libraries which are then added in the APK. You can get a clear idea about this process from the below diagram.In this way, Desugaring works and it provides backward compatibility for new Java libraries in the devices with lower API levels. "}, {"text": "\nSlider Date Picker in Android\n\nSlider Date Picker is one of the most popular features that we see in most apps. We can get to see this Slider date picker in most of the travel planning applications, Ticket booking services, and many more. Using Slider date Picker makes it efficient to pick the date. In this article, we are going to see how to implement Slider Date Picker in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Applications of Slider Date PickerThe most common application of this Slider date picker is it is used in most travel planning apps.\nThis Date Picker can also be seen in Ticket Booking services.\nYou can get to see this Slider Date Picker in the exam form filling application.Attributes of Slider Date PickerAttributesDescription.setStartDate()\nTo set the starting Date of the Calendar..setEndDate()\nTo set the ending Date of the Calendar..setThemeColor()\nTo set the theme Color..setHeaderTextColor()\nTo set the header text Color..setHeaderDateFormat()\nTo set the Date Format..setShowYear()\nTo show the current year..setCancelText()\nTo cancel text..setConfirmText()\nTo confirm text..setPreselectedDate()\nTo select today\u2019s date.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add dependency and JitPack Repository\nNavigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation \u2018com.github.niwattep:material-slide-date-picker:v2.0.0\u2019Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.allprojects {\nrepositories {\n \u2026\n maven { url \u201chttps://jitpack.io\u201d }\n }\n}After adding this dependency sync your project and now we will move towards its implementation. \nStep 3: Create a new Slider Date Picker in your activity_main.xml file\nNavigate 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 \n\n\nStep 4: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import com.niwattep.materialslidedatepicker.SlideDatePickerDialog;\nimport com.niwattep.materialslidedatepicker.SlideDatePickerDialogCallback;import java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Locale;public class MainActivity extends AppCompatActivity implements SlideDatePickerDialogCallback {// Initialize textview and button\nButton button;\nTextView textView;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// button and text view called using id\nbutton = findViewById(R.id.button);\ntextView = findViewById(R.id.textView);button.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View view) {\nCalendar endDate = Calendar.getInstance();\nendDate.set(Calendar.YEAR, 2100);\nSlideDatePickerDialog.Builder builder = new SlideDatePickerDialog.Builder();\nbuilder.setEndDate(endDate);\nSlideDatePickerDialog dialog = builder.build();\ndialog.show(getSupportFragmentManager(), \"Dialog\");\n}\n});\n}// date picker\n@Override\npublic void onPositiveClick(int date, int month, int year, Calendar calendar) {\nSimpleDateFormat format = new SimpleDateFormat(\"EEEE, MMM dd, yyyy\", Locale.getDefault());\ntextView.setText(format.format(calendar.getTime()));\n}\n}Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210120095139/Screenrecorder-2021-01-20-09-49-15-998.mp4"}, {"text": "\nHow to Install and Uninstall Plugins in Android Studio?\n\nAndroid Studio provides a platform where one can build apps for Android phones, tablets, Android Wear, Android TV, and Android Auto. Android Studio is the official IDE for Android application development, and it is based on the IntelliJ IDEA. One can develop Android Applications using Kotlin or Java as the Backend Language and it provides XML for developing Frontend Screens.In computing, a plug-in is a software component that adds a particular characteristic to an existing computer program. When a program supports plug-ins, it enables customization. Plugins are a great way to increase productivity and overall programming experience.\u2063\u2063Some tasks are boring and not fun to do, by using plugins in the android studio you can get more done in less time. Below is the list of some very useful plugins in the table that are highly recommendable for an android developer.PluginsDescriptionKey Promoter X\nKey Promoter X helps to get the necessary shortcuts while working on android projects. When the developers use the mouse on a button inside the IDE, the Key Promoter X shows the keyboard shortcut that you should have used instead.Json To Kotlin Class\nJson to Kotlin Class is a plugin to generate Kotlin data class from JSON string, in another word, a plugin that converts JSON string to Kotlin data class. With this, you can generate a Kotlin data class from the JSON string programmatically.Rainbow Brackets\nRainbow Brackets adds rainbow brackets and rainbows parentheses to the code. Color coding the brackets makes it simpler to obtain paired brackets so that the developers don\u2019t get lost in a sea of identical brackets. This is a very helpful tool and saves the confusion of selecting which bracket needs to be closed.CodeGlance\nCodeglance plugin illustrates a zoomed-out overview or minimap similar to the one found in Sublime into the editor pane. The minimap enables fast scrolling letting you jump straight to sections of code.ADB Idea\nADB Idea is a plugin for Android Studio and Intellij IDEA that speeds up the regular android development. It allows shortcuts for different emulator functionalities that are usually very time consuming, like resetting our app data, uninstalling our app, or starting the debugger.Step by Step Process to Install and Uninstall Plugins in Android Studio\nStep 1: Open the Android Studio and go to File > Settings as shown in the below image.Step 2: After hitting on the Settings button a pop-up screen will arise like the following. Here select Plugins in the left panel. Make sure you are on the Marketplace tab. Then search for the required plugins as per the developer\u2019s requirements. After selecting the required plugins then click on the green colors Install button at the right and at last click on the OK button below.Note: There might be a need to Restart the Android Studio. For example, you may refer to How to Install Genymotion Plugin to Android Studio.After these brief steps, you have your plugin installed and functional on Android Studio. Similarly if one wants to disable or uninstall the installed plugins then follow the last step.\nStep 3: To disable or uninstall a plugin this time go to the Installed tab. And here you can find the all installed plugins in your android studio. Just click on that plugin which one you want to disable or uninstall. Then select the Disable or Uninstall button at the right as shown in the below image. At last click on the OK button and you are done.Note: There might be a need to Restart the Android Studio."}, {"text": "\nDatePicker in Kotlin\n\nAndroid DatePicker is a user interface control which is used to select the date by day, month and year in our android application. DatePicker is used to ensure that the users will select a valid date.In android DatePicker having two modes, first one to show the complete calendar and second one shows the dates in spinner view.We can create a DatePicker control in two ways either manually in XML file or create it in Activity file programmatically.First we create a new project by following the below steps:Click on File, then New => New Project.\nAfter that include the Kotlin support and click on next.\nSelect the minimum SDK as per convenience and click next button.\nThen select the Empty activity => next => finish.Android DatePicker with Calendar mode\nWe can use android:datePickerMode to show only calendar view. In the below example, we are using the DatePicker in Calendar mode.XML The above code of DatePicker can be seen in android application like thisAndroid DatePicker with Spinner mode\nWe can also show the DatePicker in spinner format like selecting the day, month and year separately, by using android:datePickerMode attribute and set android:calendarViewShown=\u201dfalse\u201d, otherwise both spinner and calendar can be seen simultaneously.XML The above code of DatePicker can be seen in android application like thisDifferent attributes of DatePicker control \u2013XML Attributes\nDescriptionandroid:id\nUsed to uniquely identify the control.android:datePickerMode\nUsed to specify the mode of datepicker(spinner or calendar)android:calendarTextColor\nUsed to specify the color of the text.android:calendarViewShown\nUsed to specify whether view of the calendar is shown or not.android:background\nUsed to set background color of the Text View.android:padding\nUsed to set the padding from left, right, top and bottom.To use Calendar DatePicker in activity_main.xml\nIn this file, we will add the DatePicker and Button widget and set their attributes so that it can be accessed in the kotlin file.XML \n To use Spinner DatePicker in activity_main.xml\nIn this file, we will add the DatePicker and Button widget and set their attributes so that it can be accessed in the kotlin file.XML \n Modify the strings.xml file to add the string-array\nHere, we will specify the name of the activity.XML \nDatePickerInKotlin \n Access the DatePicker in MainActivity.kt file\nFirst of all, we declare a variable datePicker to access the DatePicker widget from the XML layout.\nval datePicker = findViewById(R.id.date_Picker)\nthen, we declare another variable today to get the current get like this.\nval today = Calendar.getInstance()\n datePicker.init(today.get(Calendar.YEAR), today.get(Calendar.MONTH),\n today.get(Calendar.DAY_OF_MONTH)\nTo display the selected date from the calendar we will use\n { view, year, month, day ->\n val month = month + 1\n val msg = \"You Selected: $day/$month/$year\"\n Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()\n }\nWe are familiar with further activities in previous articles like accessing button and set OnClickListener etc.Kotlin package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport android.widget.* \nimport java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) val datePicker = findViewById(R.id.date_Picker) \nval today = Calendar.getInstance() \ndatePicker.init(today.get(Calendar.YEAR), today.get(Calendar.MONTH), \ntoday.get(Calendar.DAY_OF_MONTH) ) { view, year, month, day -> \nval month = month + 1\nval msg = \"You Selected: $day/$month/$year\"\nToast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show() \n} \n} \n} AndroidManifest.xml fileXML \n \n \n \n \n \n \n Run as Emulator:"}, {"text": "\nHow to Add WaveLineView in Android?\n\nIn this article, WaveLineView is implemented in android. WaveLineView provides us with a very beautiful UI. It can be used when the user has to wait for some time. WaveLineView makes our layout very attractive and hence enhancing the user experience of the app. WaveLineView provide two methods startAnim() and stopAnim(). WaveLineView can be used wherever the developer wants the user to wait for some time. Also, Progress Bar can be used instead of this but because of its unique UI, it will attract users and hence users wait for enough time. It also provides full control to Developers as they can customize it according to the requirements.\nStep By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Add the Required Dependencies\nNavigate to the Gradle Scripts > build.gradle(Module:app) and Add the Below Dependency in the Dependencies section.\nimplementation 'com.github.Jay-Goo:WaveLineView:v1.0.4'\nAdd the Support Library in your settings.gradle File. This library Jitpack is a novel package repository. It is made for JVM so that any library which is present in Github and Bitbucket can be directly used in the application.\ndependencyResolutionManagement {\n repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)\n repositories {\n google()\n mavenCentral()\n \n // add the following\n maven { url \"https://jitpack.io\" }\n }\n}\nAfter adding this Dependency, Sync the Project and now we will move towards its implementation.\nStep 3: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail. In this file, we add WaveLineView to the layout.XML \n\nStep 4: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. WaveLineView provide us two method startAnim() and stopAnim(). startAnim() start the animation and stopAnim() stops it.Java import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport jaygoo.widget.wlv.WaveLineView;public class MainActivity extends AppCompatActivity {WaveLineView waveLineView;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);waveLineView = findViewById(R.id.waveLineView);\nwaveLineView.startAnim();\n}\n}Kotlin import android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nimport jaygoo.widget.wlv.WaveLineViewclass MainActivity : AppCompatActivity() {private lateinit var waveLineView: WaveLineViewoverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)waveLineView = findViewById(R.id.waveLineView)\nwaveLineView.startAnim()\n}\n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20200709215403/Record_2020-07-09-21-49-10_6a33b8dc17ce0e45bec163fe538b18f01.mp4"}, {"text": "\nHow to Implement YoutubePlayerView Library in Android?\n\nIf you are looking to display YouTube videos inside your app without redirecting your user from your app to YouTube then this library is very helpful for you to use. With the help of this library, you can simply play videos from YouTube with the help of a video id inside your app itself without redirecting your user to YouTube. Now we will see the implementation of this library in our Android App. We are going toimplement this project using both Java and Kotlin Programming Language for Android.\nStep by Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Add the JAR File inside the Libs Folder in Android Studio\nDownload the JAR file from this link. To add this file open your android project in \u201cProject\u201d mode as shown in the below image.Then go to Your Project Name > app > libs and right-click on it and paste the downloaded JAR files. You may also refer to the below image.Note: You may also refer to this article How to Import External JAR Files in Android Studio?Step 3: Adding Dependency to the build.gradle File\nGo to Module build.gradle file and add this dependency.\nimplementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:10.0.3'\nNow click on the \u201csync now\u201d option which you will get to see in the top right corner after adding this library. After that, we are ready for integrating the YouTube video player into the app.\nStep 4: Working with the activity_main.xml File\nNow change the project tab in the top left corner to Android. After that navigate to the app > res > layout > activity_main.xml. Inside this, we will create a simple button that will redirect to a new activity where we will play our YouTube video. Below is the XML code snippet for the activity_main.xml file.XML \n \n \nStep 5: Create a New Empty Activity\nNow we will create a new activity where we will display our YouTube video player. To create a new activity navigate to the app > java > your app\u2019s package name and right-click on it > New > Activity > Empty Activity > Give a name to your activity and select Java/Kotlin as its language. Now your new activity has been created. (Here we have given the activity name as VideoPlayerActivity).\nStep 6: Implement YoutubePlayerView inside the New Activity\nBelow is the code for the activity_video_player.xml file.XML \n \n \n \nStep 7: Working with the VideoPlayerActivity File\nBefore working with the VideoPlayerActivity file let\u2019s have a look at how to get the video id of any YouTube video.Open YouTube and search for any video which you want to play inside your app. Play that video inside your browser. In the top section of your browser, there will be an address bar where you can get to see the URL for that video. For example, here we have taken the below URL.\nhttps://www.youtube.com/watch?v=vG2PNdI8axo\nInside the above URL, the video ID is present in the extreme left part i.e after the v = sign is your video id. In the above example, the video ID will be\nvG2PNdI8axo \nIn this way, we can get the URL for any video. Now go to the VideoPlayerActivity file and refer to the following code. Below is the code for the VideoPlayerActivity file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.view.Window; \nimport android.view.WindowManager; \nimport androidx.annotation.NonNull; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.PlayerConstants; \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer; \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener; \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView; public class VideoPlayerActivity extends AppCompatActivity { // id of the video which we are playing. \nString video_id = \"vG2PNdI8axo\"; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); // below two lines are used to set our screen orientation in landscape mode. \nrequestWindowFeature(Window.FEATURE_NO_TITLE); \ngetWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_video_player); // below line of code is to hide our action bar. \ngetSupportActionBar().hide(); // declaring variable for youtubePlayer view \nfinal YouTubePlayerView youTubePlayerView = findViewById(R.id.videoPlayer); // below line is to place your youtube player in a full screen mode (i.e landscape mode) \nyouTubePlayerView.enterFullScreen(); \nyouTubePlayerView.toggleFullScreen(); // here we are adding observer to our youtubeplayerview. \ngetLifecycle().addObserver(youTubePlayerView); // below method will provides us the youtube player ui controller such \n// as to play and pause a video to forward a video and many more features. \nyouTubePlayerView.getPlayerUiController(); // below line is to enter full screen mode. \nyouTubePlayerView.enterFullScreen(); \nyouTubePlayerView.toggleFullScreen(); // adding listener for our youtube player view. \nyouTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() { \n@Override\npublic void onReady(@NonNull YouTubePlayer youTubePlayer) { \n// loading the selected video into the YouTube Player \nyouTubePlayer.loadVideo(video_id, 0); \n} @Override\npublic void onStateChange(@NonNull YouTubePlayer youTubePlayer, @NonNull PlayerConstants.PlayerState state) { \n// this method is called if video has ended, \nsuper.onStateChange(youTubePlayer, state); \n} \n}); \n} \n}Kotlin import android.os.Bundle \nimport android.view.Window \nimport android.view.WindowManager \nimport androidx.appcompat.app.AppCompatActivity \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.PlayerConstants \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView class VideoPlayerActivity : AppCompatActivity() { // id of the video which we are playing. \nvar video_id = \"vG2PNdI8axo\"override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) // below two lines are used to set our screen orientation in landscape mode. \nrequestWindowFeature(Window.FEATURE_NO_TITLE) \nwindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) setContentView(R.layout.activity_video_player) // below line of code is to hide our action bar. \nsupportActionBar?.hide() // declaring variable for youtubePlayer view \nval youTubePlayerView: YouTubePlayerView = findViewById(R.id.videoPlayer) // below line is to place your youtube player in a full screen mode (i.e landscape mode) \nyouTubePlayerView.enterFullScreen() \nyouTubePlayerView.toggleFullScreen() // here we are adding observer to our youtubeplayerview. \nlifecycle.addObserver(youTubePlayerView) // below method will provides us the youtube player ui controller such \n// as to play and pause a video to forward a video and many more features. \nyouTubePlayerView.getPlayerUiController() // below line is to enter full screen mode. \nyouTubePlayerView.enterFullScreen() \nyouTubePlayerView.toggleFullScreen() // adding listener for our youtube player view. \nyouTubePlayerView.addYouTubePlayerListener(object : AbstractYouTubePlayerListener() { \nfun onReady(youTubePlayer: YouTubePlayer) { \n// loading the selected video into the YouTube Player \nyouTubePlayer.loadVideo(video_id, 0) \n} fun onStateChange(youTubePlayer: YouTubePlayer, state: PlayerConstants.PlayerState) { \n// this method is called if video has ended, \nsuper.onStateChange(youTubePlayer, state) \n} \n}) \n} \n}Step 8: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Java import android.content.Intent; \nimport android.os.Bundle; \nimport android.widget.Button; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // variable for our button \nButton playBtn; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Initialize our Button \nplayBtn = findViewById(R.id.idBtnPlayVideo); // we have set onclick listener for our button \nplayBtn.setOnClickListener(v -> { \n// we have declared an intent to open new activity. \nIntent i = new Intent(MainActivity.this, VideoPlayerActivity.class); \nstartActivity(i); \n}); \n} \n}Kotlin import android.content.Intent \nimport android.os.Bundle \nimport android.widget.Button \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // variable for our button \nlateinit var playBtn: Button override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Initialize our Button \nplayBtn = findViewById(R.id.idBtnPlayVideo) // we have set onclick listener for our button \nplayBtn.setOnClickListener { \n// we have declared an intent to open new activity. \nval i = Intent(this, VideoPlayerActivity::class.java) \nstartActivity(i) \n} \n} \n}Step 9: Adding Permissions to the AndroidManifest.xml File\nIn AndroidManifest.xml, one needs to include the below permission, in order to access the internet. Navigate to the app > AndroidManifest.xml file there you have to add the below permissions.\n \n \n\nAlong with this, you will get to see an activity section inside your application tag. Inside that, add your video player\u2019s activity screen orientation to landscape mode.\n\n\n \nBelow is the code for the complete AndroidManifest.xml file:XML \n \n \n \n \n \n \n \n \n \n \nOutput: Run the App on a Physical Devicehttps://media.geeksforgeeks.org/wp-content/uploads/20201214160612/Screenrecorder-2020-12-14-15-53-30-976.mp4\nCheck out the project on the below GitHub link: https://github.com/ChaitanyaMunje/YoutubePlayerView"}, {"text": "\nHow to create a Stopwatch App using Android Studio\n\nIn this article, an Android app is created to display a basic Stopwatch.\nThe layout for Stopwatch includes:A TextView: showing how much time has passed\nThree Buttons:Start: To start the stopwatch\nStop: To stop the stopwatch\nReset: To reset the stopwatch to 00:00:00Steps to create the Stopwatch:Create a new project for Stopwatch App\nAdd String resources\nUpdate the Stopwatch layout code\nUpdate the code for activityBelow are the steps one by one in detail:Create a new project for Stopwatch AppCreate a new Android project for an application named \u201cStopwatch\u201d with a company domain of \u201cgeeksforgeeks.org\u201d, making the package name org.geeksforgeeks.stopwatch.\nCreate a New project and select Empty Activity\nConfigure the projectThe minimum SDK should be API 14 so it can run on almost all devices.\nAn empty activity called \u201cStopwatchActivity\u201d and a layout called \u201cactivity_stopwatch\u201d will be created.\nFirst opening screenAdd String resources\nWe are going to use three String values in our stopwatch layout, one for the text value of each button. These values are String resources, so they need to be added to strings.xml. Add the String values below to your version of strings.xml:Strings.xml \nGFG|Stopwatch \nStart \nStop \nReset \n Update the Stopwatch layout code\nHere is the XML for the layout. It describes a single text view that\u2019s used to display the timer, and three buttons to control the stopwatch. Replace the XML currently in activity_stopwatch.xml with the XML shown here:activity_stopwatch.xml \n\nandroid:background=\"#0F9D58\" \nandroid:padding=\"16dp\" \ntools:context=\"org.geeksforgeeks.stopwatch.StopwatchActivity\"> \n\nandroid:id=\"@+id/time_view\" \nandroid:layout_width=\"wrap_content\" \nandroid:layout_height=\"wrap_content\" \nandroid:layout_gravity=\"center_horizontal\" \n\nandroid:textAppearance=\"@android:style/TextAppearance.Large\" \nandroid:textSize=\"56sp\" /> \n\nandroid:onClick=\"onClickStart\" \nandroid:text=\"@string/start\" /> \n\nandroid:id=\"@+id/stop_button\" \nandroid:layout_width=\"wrap_content\" \nandroid:layout_height=\"wrap_content\" \nandroid:layout_gravity=\"center_horizontal\" \nandroid:layout_marginTop=\"8dp\" \n\nandroid:onClick=\"onClickStop\" \nandroid:text=\"@string/stop\" /> \n\nandroid:id=\"@+id/reset_button\" \nandroid:layout_width=\"wrap_content\" \nandroid:layout_height=\"wrap_content\" \nandroid:layout_gravity=\"center_horizontal\" \nandroid:layout_marginTop=\"8dp\" \n\nandroid:onClick=\"onClickReset\" \nandroid:text=\"@string/reset\" /> \n How the activity code will work\nThe layout defines three buttons that we will use to control the stopwatch. Each button uses its onClick attribute to specify which method in the activity should run when the button is clicked. When the Start button is clicked, the onClickStart() method gets called, when the Stop button is clicked the onClickStop() method gets called, and when the Reset button is clicked the onClickReset() method gets called. We will use these methods to start, stop and reset the stopwatch.\nWe will update the stopwatch using a method we will create called runTimer(). The runTimer() method will run code every second to check whether the stopwatch is running, and, if it is, increment the number of seconds and display the number of seconds in the text view.\nTo help us with this, we will use two private variables to record the state of the stopwatch. We will use an int called seconds to track how many seconds have passed since the stopwatch started running, and a boolean called running to record whether the stopwatch is currently running.\nWe will start by writing the code for the buttons, and then we will look at the runTimer() method.Add code for the buttons When the user clicks on the Start button, we will set the running variable to true so that the stopwatch will start. When the user clicks on the Stop button, we will set running to false so that the stopwatch stops running. If the user clicks on the Reset button, we will set running to false and seconds to 0 so that the stopwatch is reset and stops running.The runTimer() method The next thing we need to do is to create the runTimer() method. This method will get a reference to the text view in the layout; format the contents of the seconds variable into hours, minutes, and seconds; and then display the results in the text view. If the running variable is set to true, it will increment the seconds variable.Handlers allow you to schedule code A Handler is an Android class you can use to schedule code that should be run at some point in the future. You can also use it to post code that needs to run on a different thread than the main Android thread. In our case, we are going to use a Handler to schedule the stopwatch code to run every second.\nTo use the Handler, you wrap the code you wish to schedule in a Runnable object, and then use the Handle post() and postDelayed() methods to specify when you want the code to run.The post() method The post() method posts code that needs to be run as soon as possible(which is usually immediately). This method takes one parameter, an object of type Runnable. A Runnable object in Androidville is just like a Runnable in plain old Java: a job you want to run. You put the code you want to run in the Runnable\u2019s run() method, and the Handler will make sure the code is run as soon as possible.The postDelayed() method The postDelayed() method works in a similar way to the post() method except that you use it to post code that should be run in the future. The postDelayed() method takes two parameters: a Runnable and a long. The Runnable contains the code you want to run in its run() method, and the long specifies the number of milliseconds you wish to delay the code by. The code will run as soon as possible after the delay.Below is the following code to StopwatchActivity.java:StopwatchActivity.java package org.geeksforgeeks.stopwatch; import android.app.Activity; \nimport android.os.Handler; \nimport android.view.View; \nimport android.os.Bundle; \nimport java.util.Locale; \nimport android.widget.TextView; public class StopwatchActivity extends Activity { // Use seconds, running and wasRunning respectively \n// to record the number of seconds passed, \n// whether the stopwatch is running and \n// whether the stopwatch was running \n// before the activity was paused. // Number of seconds displayed \n// on the stopwatch. \nprivate int seconds = 0; // Is the stopwatch running? \nprivate boolean running; private boolean wasRunning; @Override\nprotected void onCreate(Bundle savedInstanceState) \n{ \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_stopwatch); \nif (savedInstanceState != null) { // Get the previous state of the stopwatch \n// if the activity has been \n// destroyed and recreated. \nseconds \n= savedInstanceState \n.getInt(\"seconds\"); \nrunning \n= savedInstanceState \n.getBoolean(\"running\"); \nwasRunning \n= savedInstanceState \n.getBoolean(\"wasRunning\"); \n} \nrunTimer(); \n} // Save the state of the stopwatch \n// if it's about to be destroyed. \n@Override\npublic void onSaveInstanceState( \nBundle savedInstanceState) \n{ \nsavedInstanceState \n.putInt(\"seconds\", seconds); \nsavedInstanceState \n.putBoolean(\"running\", running); \nsavedInstanceState \n.putBoolean(\"wasRunning\", wasRunning); \n} // If the activity is paused, \n// stop the stopwatch. \n@Override\nprotected void onPause() \n{ \nsuper.onPause(); \nwasRunning = running; \nrunning = false; \n} // If the activity is resumed, \n// start the stopwatch \n// again if it was running previously. \n@Override\nprotected void onResume() \n{ \nsuper.onResume(); \nif (wasRunning) { \nrunning = true; \n} \n} // Start the stopwatch running \n// when the Start button is clicked. \n// Below method gets called \n// when the Start button is clicked. \npublic void onClickStart(View view) \n{ \nrunning = true; \n} // Stop the stopwatch running \n// when the Stop button is clicked. \n// Below method gets called \n// when the Stop button is clicked. \npublic void onClickStop(View view) \n{ \nrunning = false; \n} // Reset the stopwatch when \n// the Reset button is clicked. \n// Below method gets called \n// when the Reset button is clicked. \npublic void onClickReset(View view) \n{ \nrunning = false; \nseconds = 0; \n} // Sets the NUmber of seconds on the timer. \n// The runTimer() method uses a Handler \n// to increment the seconds and \n// update the text view. \nprivate void runTimer() \n{ // Get the text view. \nfinal TextView timeView \n= (TextView)findViewById( \nR.id.time_view); // Creates a new Handler \nfinal Handler handler \n= new Handler(); // Call the post() method, \n// passing in a new Runnable. \n// The post() method processes \n// code without a delay, \n// so the code in the Runnable \n// will run almost immediately. \nhandler.post(new Runnable() { \n@Overridepublic void run() \n{ \nint hours = seconds / 3600; \nint minutes = (seconds % 3600) / 60; \nint secs = seconds % 60; // Format the seconds into hours, minutes, \n// and seconds. \nString time \n= String \n.format(Locale.getDefault(), \n\"%d:%02d:%02d\", hours, \nminutes, secs); // Set the text view text. \ntimeView.setText(time); // If running is true, increment the \n// seconds variable. \nif (running) { \nseconds++; \n} // Post the code again \n// with a delay of 1 second. \nhandler.postDelayed(this, 1000); \n} \n}); \n} \n} Output:\nOutput of Stopwatch App."}, {"text": "\nAndroid App Development Fundamentals for Beginners\n\nAndroid is an operating system that is built basically for Mobile phones. It is based on the Linux Kernel and other open-source software and is developed by Google. It is used for touchscreen mobile devices such as smartphones and tablets. But nowadays these are used in Android Auto cars, TV, watches, camera, etc. It has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought in 2005. Various applications (apps) like games, music player, camera, etc. are built for these smartphones for running on Android. Google Play store features more than 3.3 million apps. The app is developed on an application known as Android Studio. These executable apps are installed through a bundle or package called APK(Android Package Kit).\nAndroid Fundamentals\n1. Android Programming Languages\nIn Android, basically, programming is done in two languages JAVA or C++ and XML(Extension Markup Language). Nowadays KOTLIN is also preferred. The XML file deals with the design, presentation, layouts, blueprint, etc (as a front-end) while the JAVA or KOTLIN deals with the working of buttons, variables, storing, etc (as a back-end).\n2. Android Components\nThe App components are the building blocks of Android. Each component has its own role and life cycles i.e from launching of an app till the end. Some of these components depend upon others also. Each component has a definite purpose. The four major app components are:Activities\nServices\nBroadcast Receivers:\nContent Provider:Activities: It deals with the UI and the user interactions to the screen. In other words, it is a User Interface that contains activities. These can be one or more depending upon the App. It starts when the application is launched. At least one activity is always present which is known as MainActivity. The activity is implemented through the following. \nSyntax:\npublic class MainActivity extends Activity{\n // processes\n}\nTo know more Activities please refer to this article: Introduction to Activities in Android\nServices: Services are the background actions performed by the app, these might be long-running operations like a user playing music while surfing the Internet. A service might need other sub-services so as to perform specific tasks. The main purpose of the Services is to provide non-stop working of the app without breaking any interaction with the user.\nSyntax:\npublic class MyServices extends Services{\n // code for the services\n}\nTo know more Services please refer to this article:Services in Android with Example\nBroadcast Receivers: A Broadcast is used to respond to messages from other applications or from the System. For example, when the battery of the phone is low, then the Android OS fires a Broadcasting message to launch the Battery Saver function or app, after receiving the message the appropriate action is taken by the app. Broadcast Receiver is the subclass of BroadcastReceiver class and each object is represented by Intent objects.\nSyntax: \npublic class MyReceiver extends BroadcastReceiver{\n public void onReceive(context,intent){\n }\nTo know more Broadcast Receivers please refer to this article:Broadcast Receiver in Android With Example\nContent Provider: Content Provider is used to transferring the data from one application to the others at the request of the other application. These are handled by the class ContentResolver class. This class implements a set of APIs(Application Programming Interface) that enables the other applications to perform the transactions. Any Content Provider must implement the Parent Class of ContentProvider class.\nSyntax:\npublic class MyContentProvider extends ContentProvider{\n public void onCreate()\n {}\n}\nTo know more Content Provider please refer to this article:Content Providers in Android with Example\n3. Structural Layout Of Android Studio\nThe basic structural layout of Android Studio is given below:The above figure represents the various structure of an app.\nManifest Folder: Android Manifest is an XML file that is the root of the project source set. It describes the essential information about the app and the Android build tools, the Android Operating System, and Google Play. It contains the permission that an app might need in order to perform a specific task. It also contains the Hardware and the Software features of the app, which determines the compatibility of an app on the Play Store. It also includes special activities like services, broadcast receiver, content providers, package name, etc.\nJava Folder: The JAVA folder consists of the java files that are required to perform the background task of the app. It consists of the functionality of the buttons, calculation, storing, variables, toast(small popup message), programming function, etc. The number of these files depends upon the type of activities created.\nResource Folder: The res or Resource folder consists of the various resources that are used in the app. This consists of sub-folders like drawable, layout, mipmap, raw, and values. The drawable consists of the images. The layout consists of the XML files that define the user interface layout. These are stored in res.layout and are accessed as R.layout class. The raw consists of the Resources files like audio files or music files, etc. These are accessed through R.raw.filename. values are used to store the hardcoded strings(considered safe to store string values) values, integers, and colors. It consists of various other directories like:R.array :arrays.xml for resource arrays\nR.integer : integers.xml for resource integers\nR.bool : bools.xml for resource boolean\nR.color :colors.xml for color values\nR.string : strings.xml for string values\nR.dimen : dimens.xml for dimension values\nR.style : styles.xml for stylesGradle Files: Gradle is an advanced toolkit, which is used to manage the build process, that allows defining the flexible custom build configurations. Each build configuration can define its own set of code and resources while reusing the parts common to all versions of your app. The Android plugin for Gradle works with the build toolkit to provide processes and configurable settings that are specific to building and testing Android applications. Gradle and the Android plugin run independently of Android Studio. This means that you can build your Android apps from within Android Studio. The flexibility of the Android build system enables you to perform custom build configurations without modifying your app\u2019s core source files.\nBasic Layout Can be defined in a tree structure as:\nProject/\n app/\n manifest/\n AndroidManifest.xml\n java/\n MyActivity.java \n res/\n drawable/ \n icon.png\n background.png\n drawable-hdpi/ \n icon.png\n background.png \n layout/ \n activity_main.xml\n info.xml\n values/ \n strings.xml \n4. Lifecycle of Activity in Android App\nThe Lifecycle of Activity in Android App can be shown through this diagram:States of Android Lifecycle:OnCreate: This is called when activity is first created.\nOnStart: This is called when the activity becomes visible to the user.\nOnResume: This is called when the activity starts to interact with the user.\nOnPause: This is called when activity is not visible to the user.\nOnStop: This is called when activity is no longer visible.\nOnRestart: This is called when activity is stopped, and restarted again.\nOnDestroy: This is called when activity is to be closed or destroyed.To know more about Activity Lifecycle in Android Please refer to this article: Activity Lifecycle in Android with Demo App\nTo begin your journey in Android you may refer to these tutorials:Android Tutorial\nKotlin Android Tutorial\nAndroid Studio Tutorial\nAndroid Projects \u2013 From Basic to Advanced Level"}, {"text": "\nDynamic Switch in Kotlin\n\nAndroid Switch is also a two-state user interface element that is used to toggle between ON and OFF as a button. By touching the button we can drag it back and forth to make it either ON or OFF.The Switch element is useful when only two states require for activity either choose ON or OFF. We can add a Switch to our application layout by using the Switch object. By default, the state for the android Switch is OFF state. We can also change the state of Switch to ON by setting the android:checked = \u201ctrue\u201d in our XML layout file.In android, we can create Switch control in two ways either by using Switch in XML layout file or creating it in Kotlin file dynamically.First, we create a new project by following the below steps:Click on File, then New => New Project.\nAfter that include the Kotlin support and click on next.\nSelect the minimum SDK as per convenience and click next button.\nThen select the Empty activity => next => finish.LinearLayout in activity_main.xml file\nIn this file, we use the LinearLayout and can not add the switch widget manually because it will be created dynamically in Kotlin file.XML \nAdd application name in strings.xml fileHere, we can put all the strings which can be used in the application in any file. So, we update the app_name which can be seen at the top of the activity.XML \nDynamicSwitchInKotlin\nCreating switches programmatically in MainActivity.kt file\nHere, we initialize and define two switches and add dynamically by calling on the linearLayout.\nlinearLayout?.addView(switch1)\nlinearLayout?.addView(switch2)\nthen, set OnClickListener on both the switches for functioning like toggle of button and Toast message like this.\nswitch1.setOnCheckedChangeListener { buttonView, isChecked ->\n val msg = if (isChecked) \"SW1:ON\" else \"SW1:OFF\"\n Toast.makeText(this@MainActivity, msg,\n Toast.LENGTH_SHORT).show()\n }\nComplete code for the Kotlin file is below.Kotlin package com.geeksforgeeks.myfirstkotlinapp\nimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.view.ViewGroup\nimport android.widget.LinearLayout\nimport android.widget.Switch\nimport android.widget.Toastclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// Creating switch1 and switch2 programmatically\nval switch1 = Switch(this)\nval layoutParams = LinearLayout.LayoutParams(ViewGroup.\nLayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)\nswitch1.layoutParams = layoutParams\nswitch1.text = \"Switch1\"val switch2 = Switch(this)\nval layoutParams2 = LinearLayout.LayoutParams(ViewGroup.\nLayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)\nswitch2.layoutParams = layoutParams2\nswitch2.text = \"Switch2\"val linearLayout = findViewById(R.id.rootContainer)\n// Adding Switches to LinearLayout\nlinearLayout?.addView(switch1)\nlinearLayout?.addView(switch2)switch1.setOnCheckedChangeListener { buttonView, isChecked ->\nval msg = if (isChecked) \"SW1:ON\" else \"SW1:OFF\"\nToast.makeText(this@MainActivity, msg,\nToast.LENGTH_SHORT).show()\n}switch2.setOnCheckedChangeListener { buttonView, isChecked ->\nval msg = if (isChecked) \"SW2:ON\" else \"SW2:OFF\"\nToast.makeText(this@MainActivity, msg,\nToast.LENGTH_SHORT).show()\n}\n}\n}AndroidManifest.xml fileXML \n\n\n\n\n\n\nRun as emulator for Output:"}, {"text": "\nWelcome to The Modern Android App Development\n\nWith the spread of smartphones, smartphone technology improved exponentially and thus smartphones occupied a huge part of the market. To meet the requirement of the user and seeing the wide-open market there came different operating systems like Android, iOS, etc but for the sake of this article, we gonna talk specifically about how Android Development changed and what it looks like today. Today for making an Android App you don\u2019t need to learn any programming language. Little strange, right!. Yes, but, indeed, you don\u2019t need to learn programming language but you just need to have problem-solving skills. I know that learning programming language teaches that but when we say you don\u2019t need programming language it means you don\u2019t need to learn syntax and semantics and the process is too visual that it doesn\u2019t feel like coding when in reality you are doing exactly \u201ccoding\u201d. And Yes we will learn to create a simple Android App from this article itself, so enjoy reading!\nHow Modern Android App Development Looks Like\nBlocky is the modern way of creating android apps. Instead of traditionally coding in an IDE in Blocky represent coding concepts in form of interlocking blocksThese interlocking blocks make it easier to visualize and help in capturing the flow of the program. Blocky is an open-source library that helps us in visualizing the blocks and using blocky there are several platforms that let us create android apps. MIT App Inventor is an open-source platform that let\u2019s use blocky for creating the android app. In this modern way, developers develop the app in two sections:Designer: The designer creates the User Interface (UI) with several pre-existing components by drag and drop.\nBlocks: Blocks do all the logic work and are used to change several properties of components used in the designer.Let\u2019s Build a Simple Hello World App\nRequirements\nAs blocky is a javascript library this helps us to create android apps directly from your web browser and thus you need:Browser\nInternet ConnectionNote: Offline mode also exists.Step by Step Implementation\nStep 1: Go to MIT App Inventor\u2019s creator and log in your using google account and click \u201cstart new project\u201cStep 2: Enter your project name and click \u201cOK\u201cStep 3: Your empty project will look like this.Step 4:Now drag and drop the \u201cButton\u201d and \u201cLabel\u201d components from Palette.Step 5:Click on the \u201cButton\u201d component which we dragged and then from right from \u201cproperties\u201d change \u201cButton Text\u201d to \u201cClick Me\u201d similarly select \u201clabel\u201d and change \u201clabel Text\u201d to an empty string.Note: Label disappears because we changed its text to an empty string.Step 6:That is enough for the Designer view now to switch to \u201cBlock\u201d from the top right corner. Click on a component to access respective blocks and drag and drop the required one.We will use simple logic. When the user clicks on the button app must change the label text to \u201cHello World!\u201dOur app is ready now we just need to export in. From the menu click \u201cBuild\u201d and select whether you want to apk to be downloaded to the computer or generate a downloadable QR code with a link. Now simply install it on your device.\nOutput:Conclusion\nModern Android app development is a very fast and efficient way of developing apps without learning any language. However, it isn\u2019t the complete replacement of native development and code. It is great for the time you need visualization and also good for introducing kids to how the program works and can be really useful for them to build their own logic and algorithms and see them working in reality.\n"}, {"text": "\nArrayAdapter in Android with Example\n\nThe Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the most commonly used adapter in android. When you have a list of single type items which are stored in an array you can use ArrayAdapter. Likewise, if you have a list of phone numbers, names, or cities. ArrayAdapter has a layout with a single TextView. If you want to have a more complex layout instead of ArrayAdapter use CustomArrayAdapter. The basic syntax for ArrayAdapter is given as:public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)ParametersParametersDescriptioncontext\nThe current context. This value can not be null.resource\nThe resource ID for the layout file containing a layout to use when instantiating views.textViewResourceId\nThe id of the TextView within the layout resource to be populated.objects\nThe objects to represent in the ListView. This value cannot be null.context: It is used to pass the reference of the current class. Here \u2018this\u2019 keyword is used to pass the current class reference. Instead of \u2018this\u2019 we could also use the getApplicationContext() method which is used for the Activity and the getApplication() method which is used for Fragments.public ArrayAdapter(this, int resource, int textViewResourceId, T[] objects)resource: It is used to set the layout file(.xml files) for the list items.public ArrayAdapter(this, R.layout.itemListView, int textViewResourceId, T[] objects)textViewResourceId: It is used to set the TextView where you want to display the text data.public ArrayAdapter(this, R.layout.itemListView, R.id.itemTextView, T[] objects)objects: These are the array object which is used to set the array element into the TextView.String courseList[] = {\u201cC-Programming\u201d, \u201cData Structure\u201d, \u201cDatabase\u201d, \u201cPython\u201d,\n \u201cJava\u201d, \u201cOperating System\u201d,\u201dCompiler Design\u201d, \u201cAndroid Development\u201d};\nArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.itemListView, R.id.itemTextView, courseList[]);Example\nIn this example, the list of courses is displayed using a simple array adapter. Note that we are going toimplement this project using theJavalanguage.\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Working with the activity_main.xml file\nGo to the layout folder and in activity_main.xml file change the ConstraintLayout to RelativeLayout and insert a ListView with id simpleListView. Below is the code for theactivity_main.xml file.XML \n Step 3: Create a new layout file\nGo to app > res > layout > right-click > New > Layout Resource File and create a new layout file and name this file as item_view.xml and make the root element as a LinearLayout. This will contain a TextView that is used to display the array objects as output.XML \n Step 4: Working with the MainActivity.java file\nNow go to the java folder and in MainActivity.java and provide the implementation to the ArrayAdapter. Below is the code for theMainActivity.java file.Java import android.os.Bundle; \nimport android.widget.ArrayAdapter; \nimport android.widget.ListView; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ListView simpleListView; // array objects \nString courseList[] = {\"C-Programming\", \"Data Structure\", \"Database\", \"Python\", \n\"Java\", \"Operating System\", \"Compiler Design\", \"Android Development\"}; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); simpleListView = (ListView) findViewById(R.id.simpleListView); ArrayAdapter arrayAdapter = new ArrayAdapter(this, \nR.layout.item_view, R.id.itemTextView, courseList); \nsimpleListView.setAdapter(arrayAdapter); \n} \n}Output: Run on Emulator"}, {"text": "\nNavigation Drawer in Android\n\nThe navigation drawer is the most common feature offered by android and the navigation drawer is a UI panel that shows your app\u2019s main navigation menu. It is also one of the important UI elements, which provides actions preferable to the users, for example changing user profile, changing settings of the application, etc. In this article, it has been discussed step by step to implement the navigation drawer in android. The code has been given in both Java and Kotlin Programming Language for Android.The navigation drawer slides in from the left and contains the navigation destinations for the app.The user can view the navigation drawer when the user swipes a finger from the left edge of the activity. They can also find it from the home activity by tapping the app icon in the action bar. The drawer icon is displayed on all top-level destinations that use a DrawerLayout. Have a look at the following image to get an idea about the Navigation drawer.Steps to Implement Navigation Drawer in Android\nStep 1: Create a New Android Studio Project\nCreate an empty activity android studio project. Refer to Android | How to Create/Start a New Project in Android Studio? on how to create an empty activity android studio project.\nStep 2: Adding a dependency to the project\nIn this discussion, we are going to use the Material Design Navigation drawer. So add the following Material design dependency to the app-level Gradle file.\nimplementation 'com.google.android.material:material:1.3.0-alpha03'\nRefer to the following image if unable to locate the app-level Gradle file that invokes the dependency (under project hierarchy view). After invoking the dependency click on the \u201cSync Now\u201d button. Make sure the system is connected to the network so that Android Studio downloads the required files.Step 3: Creating a menu in the menu folder\nCreate the menu folder under the res folder. To implement the menu. Refer to the following video to create the layout to implement the menu.https://media.geeksforgeeks.org/wp-content/uploads/20201114124319/Untitled-Project.mp4\nInvoke the following code in the navigation_menu.xmlXML \n Step 4: Working with the activity_main.xml File\nInvoke the following code in the activity_main.xml to set up the basic things required for the Navigation Drawer.XML \n \n\n Output UI:One thing to be noticed is that the menu drawer icon is still not appeared on the action bar. We need to set the icon and its open-close functionality programmatically.\nStep 5: Include the Open Close strings in the string.xml\nInvoke the following code in the app/res/values/strings.xml file.XML \nNavigation Drawer \n\nOpen \nClose \nStep 6: Working with the MainActivity FileInvoke the following code in the MainActivity file to show the menu icon on the action bar and implement the open-close functionality of the navigation drawer.\nComments are added inside the code for better understanding.Java import androidx.annotation.NonNull; \nimport androidx.appcompat.app.ActionBarDrawerToggle; \nimport androidx.appcompat.app.AppCompatActivity; \nimport androidx.drawerlayout.widget.DrawerLayout; \nimport android.os.Bundle; \nimport android.view.MenuItem; public class MainActivity extends AppCompatActivity { public DrawerLayout drawerLayout; \npublic ActionBarDrawerToggle actionBarDrawerToggle; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // drawer layout instance to toggle the menu icon to open \n// drawer and back button to close drawer \ndrawerLayout = findViewById(R.id.my_drawer_layout); \nactionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close); // pass the Open and Close toggle for the drawer layout listener \n// to toggle the button \ndrawerLayout.addDrawerListener(actionBarDrawerToggle); \nactionBarDrawerToggle.syncState(); // to make the Navigation drawer icon always appear on the action bar \ngetSupportActionBar().setDisplayHomeAsUpEnabled(true); \n} // override the onOptionsItemSelected() \n// function to implement \n// the item click listener callback \n// to open and close the navigation \n// drawer when the icon is clicked \n@Override\npublic boolean onOptionsItemSelected(@NonNull MenuItem item) { if (actionBarDrawerToggle.onOptionsItemSelected(item)) { \nreturn true; \n} \nreturn super.onOptionsItemSelected(item); \n} \n}Kotlin import android.os.Bundle \nimport android.view.MenuItem \nimport androidx.appcompat.app.ActionBarDrawerToggle \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.drawerlayout.widget.DrawerLayout class MainActivity : AppCompatActivity() { \nlateinit var drawerLayout: DrawerLayout \nlateinit var actionBarDrawerToggle: ActionBarDrawerToggle override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // drawer layout instance to toggle the menu icon to open \n// drawer and back button to close drawer \ndrawerLayout = findViewById(R.id.my_drawer_layout) \nactionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close) // pass the Open and Close toggle for the drawer layout listener \n// to toggle the button \ndrawerLayout.addDrawerListener(actionBarDrawerToggle) \nactionBarDrawerToggle.syncState() // to make the Navigation drawer icon always appear on the action bar \nsupportActionBar?.setDisplayHomeAsUpEnabled(true) \n} // override the onOptionsItemSelected() \n// function to implement \n// the item click listener callback \n// to open and close the navigation \n// drawer when the icon is clicked \noverride fun onOptionsItemSelected(item: MenuItem): Boolean { \nreturn if (actionBarDrawerToggle.onOptionsItemSelected(item)) { \ntrue\n} else super.onOptionsItemSelected(item) \n} \n}Output: Run on Emulator\nhttps://media.geeksforgeeks.org/wp-content/uploads/20201114130020/Untitled-Project.mp4"}, {"text": "\nHow to Add Mask to an EditText in Android?\n\nEditText is an android widget. It is a User Interface element used for entering and modifying data. It returns data in String format. Masking refers to the process of putting something in place of something else. Therefore by Masking an EditText, the blank space is replaced with some default text, known as Mask. This mask gets removed as soon as the user enters any character as input, and reappears when the text has been removed from the EditText. In this article, the masking is done with the help of JitPack Library, because it can be customized easily according to the need to implement various fields like phone number, date, etc. The code has been given in both Java and Kotlin Programming Language for Android.Approach:\nAdd the support Library in your settings.gradle File. This library Jitpack is a novel package repository. It is made for JVM so that any library which is present in Github and Bitbucket can be directly used in the application.\ndependencyResolutionManagement {\n repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)\n repositories {\n google()\n mavenCentral()\n \n // add the following\n maven { url \"https://jitpack.io\" }\n }\n}\nAdd the below dependency in the dependencies section of your App/Module build.gradle File. It is a simple Android EditText with custom mask support. Mask EditText is directly imported and is customized according to the use.\ndependencies {\n implementation 'ru.egslava:MaskedEditText:1.0.5'\n}\nNow add the following code in the activity_main.xml file. It will create three mask EditTexts and one button in activity_main.xml.XML \n\n\n\n\nNow add the following code in the MainActivity File. All the three mask EditTexts and a button are defined. An onClickListener() is added on the button which creates a toast and shows all the data entered in the mask EditTexts.Java import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport br.com.sapereaude.maskedEditText.MaskedEditText;public class MainActivity extends AppCompatActivity {MaskedEditText creditCardText,phoneNumText,dateText;\nButton show;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);creditCardText = findViewById(R.id.card);\nphoneNumText = findViewById(R.id.phone);\ndateText = findViewById(R.id.Date);\nshow = findViewById(R.id.showButton);show.setOnClickListener(v -> {\n// Display the information from the EditText with help of Toasts\nToast.makeText(MainActivity.this, \"Credit Card Number \" + creditCardText.getText() + \"\\n Phone Number \"\n+ phoneNumText.getText() + \"\\n Date \" + dateText.getText(), Toast.LENGTH_LONG).show();\n});\n}\n}Kotlin import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.Toast\nimport br.com.sapereaude.maskedEditText.MaskedEditTextclass MainActivity : AppCompatActivity() {lateinit var creditCardText: MaskedEditText\nlateinit var phoneNumText: MaskedEditText\nlateinit var dateText: MaskedEditText\nlateinit var show: Buttonoverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)creditCardText = findViewById(R.id.card)\nphoneNumText = findViewById(R.id.phone)\ndateText = findViewById(R.id.Date)\nshow = findViewById(R.id.showButton)show.setOnClickListener {\n// Display the information from the EditText with help of Toasts\nToast.makeText(this, (\"Credit Card Number \" + creditCardText.getText()) + \"\\n Phone Number \"\n+ phoneNumText.getText().toString() + \"\\n Date \" + dateText.getText(), Toast.LENGTH_LONG\n).show()\n}\n}\n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20200505162724/Record_2020-05-05-16-09-23_b64b62a768fef9e79b7cc5e52be67d20.mp4"}, {"text": "\nProgressBar in Android using Jetpack Compose\n\nProgressBar is a material UI component in Android which is used to indicate the progress of any process such as for showing any downloading procedure, as a placeholder screen, and many more. In this article, we will take a look at the implementation of ProressBar in Android using Jetpack Compose.AttributesUsesmodifier\nto add padding to our progress Bar.color\nto add color to our progress Bar.strokeWidth\nthis attribute is used to give the width of the circular line of the progress Bar.progress\nto indicate the progress of your circular progress Bar.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.\nStep 2: Working with the MainActivity.kt file\nNavigate to the app > java > your app\u2019s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail.Kotlin import android.graphics.drawable.shapes.Shape\nimport android.media.Image\nimport android.os.Bundle\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.compose.foundation.*\nimport androidx.compose.foundation.Text\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.shape.CircleShape\nimport androidx.compose.foundation.shape.RoundedCornerShape\nimport androidx.compose.foundation.text.KeyboardOptions\nimport androidx.compose.material.*\nimport androidx.compose.material.Icon\nimport androidx.compose.material.icons.Icons\nimport androidx.compose.material.icons.filled.AccountCircle\nimport androidx.compose.material.icons.filled.Info\nimport androidx.compose.material.icons.filled.Menu\nimport androidx.compose.material.icons.filled.Phone\nimport androidx.compose.runtime.*\nimport androidx.compose.runtime.savedinstancestate.savedInstanceState\nimport androidx.compose.ui.Alignment\nimport androidx.compose.ui.layout.ContentScale\nimport androidx.compose.ui.platform.setContent\nimport androidx.compose.ui.res.imageResource\nimport androidx.compose.ui.tooling.preview.Preview\nimport androidx.compose.ui.unit.dp\nimport com.example.gfgapp.ui.GFGAppTheme\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.draw.clip\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.graphics.SolidColor\nimport androidx.compose.ui.platform.ContextAmbient\nimport androidx.compose.ui.platform.testTag\nimport androidx.compose.ui.res.colorResource\nimport androidx.compose.ui.semantics.SemanticsProperties.ToggleableState\nimport androidx.compose.ui.text.TextStyle\nimport androidx.compose.ui.text.font.FontFamily\nimport androidx.compose.ui.text.input.*\nimport androidx.compose.ui.unit.Dp\nimport androidx.compose.ui.unit.TextUnitclass MainActivity : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContent {\nColumn {\n// in below line we are calling \n// a progress bar method.\nSimpleCircularProgressComponent()\n}\n}\n}\n}@Preview(showBackground = true)\n@Composable\nfun DefaultPreview() {\nGFGAppTheme {\nSimpleCircularProgressComponent();\n}\n}@Composable\nfun SimpleCircularProgressComponent() {\n// CircularProgressIndicator is generally used\n// at the loading screen and it indicates that\n// some progress is going on so please wait.\nColumn(\n// we are using column to align our\n// imageview to center of the screen.\nmodifier = Modifier.fillMaxWidth().fillMaxHeight(),// below line is used for specifying\n// vertical arrangement.\nverticalArrangement = Arrangement.Center,// below line is used for specifying\n// horizontal arrangement.\nhorizontalAlignment = Alignment.CenterHorizontally,) {\n// below line is use to display \n// a circular progress bar.\nCircularProgressIndicator(\n// below line is use to add padding\n// to our progress bar.\nmodifier = Modifier.padding(16.dp),// below line is use to add color \n// to our progress bar.\ncolor = colorResource(id = R.color.purple_200),// below line is use to add stroke \n// width to our progress bar.\nstrokeWidth = Dp(value = 4F)\n)\n}\n}Now run your app and see the output of the app.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210118220656/Screenrecorder-2021-01-18-22-05-28-34.mp4"}, {"text": "\nDispatchers in Kotlin Coroutines\n\nPrerequisite: Kotlin Coroutines on Android\nIt is known that coroutines are always started in a specific context, and that context describes in which threads the coroutine will be started in. In general, we can start the coroutine using GlobalScope without passing any parameters to it, this is done when we are not specifying the thread in which the coroutine should be launch. This method does not give us much control over it, as our coroutine can be launched in any thread available, due to which it is not possible to predict the thread in which our coroutines have been launched.Kotlin class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // coroutine launched in GlobalScope \nGlobalScope.launch() { \nLog.i(\"Inside Global Scope \",Thread.currentThread().name.toString()) \n// getting the name of thread in \n// which our coroutine has been launched \n} Log.i(\"Main Activity \",Thread.currentThread().name.toString()) \n} \n}log output is shown below:We can see that the thread in which the coroutine is launched cannot be predicted, sometimes it is DefaultDispatcher-worker-1, or DefaultDispatcher-worker-2 or DefaultDispatcher-worker-3.\nHow Dispatchers solve the above problem?\nDispatchers help coroutines in deciding the thread on which the work has to be done. Dispatchers are passed as the arguments to the GlobalScope by mentioning which type of dispatchers we can use depending on the work that we want the coroutine to do.\nTypes of Dispatchers\nThere are majorly 4 types of Dispatchers.Main Dispatcher\nIO Dispatcher\nDefault Dispatcher\nUnconfined DispatcherMain Dispatcher:\nIt starts the coroutine in the main thread. It is mostly used when we need to perform the UI operations within the coroutine, as UI can only be changed from the main thread(also called the UI thread).Kotlin GlobalScope.launch(Dispatchers.Main) { \nLog.i(\"Inside Global Scope \",Thread.currentThread().name.toString()) \n// getting the name of thread in which \n// our coroutine has been launched \n} \nLog.i(\"Main Activity \",Thread.currentThread().name.toString())IO Dispatcher:\nIt starts the coroutine in the IO thread, it is used to perform all the data operations such as networking, reading, or writing from the database, reading, or writing to the files eg: Fetching data from the database is an IO operation, which is done on the IO thread.Kotlin GlobalScope.launch(Dispatchers.IO) { \nLog.i(\"Inside IO dispatcher \",Thread.currentThread().name.toString()) \n// getting the name of thread in which \n// our coroutine has been launched \n} \nLog.i(\"Main Activity \",Thread.currentThread().name.toString())Default Dispatcher:\nIt starts the coroutine in the Default Thread. We should choose this when we are planning to do Complex and long-running calculations, which can block the main thread and freeze the UI eg: Suppose we need to do the 10,000 calculations and we are doing all these calculations on the UI thread ie main thread, and if we wait for the result or 10,000 calculations, till that time our main thread would be blocked, and our UI will be frozen, leading to poor user experience. So in this case we need to use the Default Thread. The default dispatcher that is used when coroutines are launched in GlobalScope is represented by Dispatchers. Default and uses a shared background pool of threads, so launch(Dispatchers.Default) { \u2026 } uses the same dispatcher as GlobalScope.launch { \u2026 }.Kotlin GlobalScope.launch(Dispatchers.Default) { \nLog.i(\"Inside Default dispatcher \",Thread.currentThread().name.toString()) \n// getting the name of thread in which \n// our coroutine has been launched \n} \nLog.i(\"Main Activity \",Thread.currentThread().name.toString())Unconfined Dispatcher:\nAs the name suggests unconfined dispatcher is not confined to any specific thread. It executes the initial continuation of a coroutine in the current call-frame and lets the coroutine resume in whatever thread that is used by the corresponding suspending function, without mandating any specific threading policy."}, {"text": "\nCircular ImageView in Android using Jetpack Compose\n\nCircular ImageView is used in many of the apps. These types of images are generally used to represent the profile picture of the user and many more images. We have seen the implementation of ImageView in Android using Jetpack Compose. In this article, we will take a look at the implementation of Circle ImageView in Android using Jetpack Compose. \nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.\nStep 2: Add an Image to the drawable folder\nAfter creating a new project we have to add an image inside our drawable folder for displaying that image inside our ImageView. Copy your image from your folder\u2019s location and go inside our project. Inside our project Navigate to the app > res > drawable > Right-click on the drawable folder and paste your image there. \nStep 3: Working with the MainActivity.kt file\nAfter adding this image navigates to the app > java > MainActivity.kt and add the below code to it. Comments are added inside the code to understand the code in more detail.Kotlin import android.graphics.drawable.shapes.Shape \nimport android.media.Image \nimport android.os.Bundle \nimport android.widget.Toast \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.compose.foundation.BorderStroke \nimport androidx.compose.foundation.Image \nimport androidx.compose.foundation.InteractionState \nimport androidx.compose.foundation.Text \nimport androidx.compose.foundation.layout.* \nimport androidx.compose.foundation.shape.CircleShape \nimport androidx.compose.foundation.shape.RoundedCornerShape \nimport androidx.compose.foundation.text.KeyboardOptions \nimport androidx.compose.material.* \nimport androidx.compose.material.icons.Icons \nimport androidx.compose.material.icons.filled.AccountCircle \nimport androidx.compose.material.icons.filled.Info \nimport androidx.compose.material.icons.filled.Phone \nimport androidx.compose.runtime.* \nimport androidx.compose.runtime.savedinstancestate.savedInstanceState \nimport androidx.compose.ui.Alignment \nimport androidx.compose.ui.layout.ContentScale \nimport androidx.compose.ui.platform.setContent \nimport androidx.compose.ui.res.imageResource \nimport androidx.compose.ui.tooling.preview.Preview \nimport androidx.compose.ui.unit.dp \nimport com.example.gfgapp.ui.GFGAppTheme \nimport androidx.compose.ui.Modifier \nimport androidx.compose.ui.draw.clip \nimport androidx.compose.ui.graphics.Color \nimport androidx.compose.ui.graphics.SolidColor \nimport androidx.compose.ui.platform.ContextAmbient \nimport androidx.compose.ui.platform.testTag \nimport androidx.compose.ui.res.colorResource \nimport androidx.compose.ui.text.TextStyle \nimport androidx.compose.ui.text.font.FontFamily \nimport androidx.compose.ui.text.input.* \nimport androidx.compose.ui.unit.Dp \nimport androidx.compose.ui.unit.TextUnit class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContent { \nGFGAppTheme { \n// A surface container using the 'background' color from the theme \nSurface(color = MaterialTheme.colors.background) { \n// at below line we are calling \n// our function for button. \nCircleImg(); \n} \n} \n} \n} \n} @Preview(showBackground = true) \n@Composable\nfun DefaultPreview() { \nGFGAppTheme { \nCircleImg(); \n} \n} @Composable\nfun CircleImg() { Column( // we are using column to align our imageview \n// to center of the screen. \nmodifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying \n// vertical arrangement. \nverticalArrangement = Arrangement.Center, // below line is used for specifying \n// horizontal arrangement. \nhorizontalAlignment = Alignment.CenterHorizontally, ) { \n// creating a card for creating a circle image view. \nCard( \n// below line is use to add size to our image view and \n// test tag is use to add tag to our image. \nmodifier = Modifier.preferredSize(100.dp).testTag(tag = \"circle\"), // below line is use to \n// add shape to our image view. \nshape = CircleShape, // below line is use to add \n// elevation to our image view. \nelevation = 12.dp \n) { \n// below line we are creating a new image. \nImage( \n// in below line we are providing image \n// resource from drawable folder. \nimageResource(id = R.drawable.gfgimage), // below line is use to give scaling \n// to our image view. \ncontentScale = ContentScale.Crop, // below line is use to add modifier \n// to our image view. \nmodifier = Modifier.fillMaxSize() \n) \n} \n} \n}Now run your app and see the output of the app.\nOutput:"}, {"text": "\nImageSwitcher in Kotlin\n\nAndroid ImageSwitcher is a user interface widget that provides a smooth transition animation effect to the images while switching between them to display in the view.\nImageSwitcher is subclass of View Switcher which is used to animates one image and displays next one.Generally, we use ImageSwitcher in two ways manually in XML layout and programmatically in Kotlin file.\nWe should define an XML component, to use ImageSwitcher in our android application.XML \n First we create a new project by following the below steps:Click on File, then New => New Project.\nAfter that include the Kotlin support and click on next.\nSelect the minimum SDK as per convenience and click next button.\nThen select the Empty activity => next => finish.Different attributes of ImageSwitcher widgetXML attributes\nDescriptionandroid:id\nUsed to specify the id of the view.android:onClick\nUsed to specify the action when this view is clicked.android:background\nUsed to set the background of the view.android:padding\nUsed to set the padding of the view.android:visibility\nUsed to set the visibility of the view.android:inAnimation\nUsed to define the animation to use when view is shown.android:outAnimation\nUsed to define the animation to use when view is hidden.android:animateFirstView\nUsed to define whether to animate the current view when the view animation is first displayed.Modify activity_main.xml file\nIn this file, we use constraint layout with ImageSwitcher and Buttons.XML \n Update strings.xml file\nHere, we update the name of the application using the string tag.XML \nImageSwitcherInKotlin \nNext \nPrev \n Different methods of ImageSwitcher widgetMethods\nDescriptionsetImageDrawable\nIt is used to set a new drawable on the next ImageView in the switcher.setImageResource\nIt is used to set a new image on the ImageSwitcher with the given resource id.setImageURI\nIt is used to set a new image on the ImageSwitcher with the given URI.Access ImageSwitcher in MainActivity.kt file\nFirst, we declare an array flowers which contains the resource of the images used for the ImageView.\nprivate val flowers = intArrayOf(R.drawable.flower1,\n R.drawable.flower2, R.drawable.flower4)\nthen, we access the ImageSwitcher from the XML layout and set ImageView to display the image.\nval imgSwitcher = findViewById(R.id.imgSw)\nimgSwitcher?.setFactory({\n val imgView = ImageView(applicationContext)\n imgView.scaleType = ImageView.ScaleType.FIT_CENTER\n imgView.setPadding(8, 8, 8, 8)\n imgView\n })\nAlso, we will use one of the above method for ImageSwitcher.\nimgSwitcher?.setImageResource(flowers[index])Kotlin package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle \nimport android.view.animation.AnimationUtils \nimport android.widget.Button \nimport android.widget.ImageSwitcher \nimport android.widget.ImageView class MainActivity : AppCompatActivity() { private val flowers = intArrayOf(R.drawable.flower1, \nR.drawable.flower2, R.drawable.flower4) \nprivate var index = 0override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // access the ImageSwitcher \nval imgSwitcher = findViewById(R.id.imgSw) imgSwitcher?.setFactory({ \nval imgView = ImageView(applicationContext) \nimgView.scaleType = ImageView.ScaleType.FIT_CENTER \nimgView.setPadding(8, 8, 8, 8) \nimgView \n}) // set the method and pass array as a parameter \nimgSwitcher?.setImageResource(flowers[index]) val imgIn = AnimationUtils.loadAnimation( \nthis, android.R.anim.slide_in_left) \nimgSwitcher?.inAnimation = imgIn val imgOut = AnimationUtils.loadAnimation( \nthis, android.R.anim.slide_out_right) \nimgSwitcher?.outAnimation = imgOut // previous button functionality \nval prev = findViewById