diff --git a/Android_Development_with_Kotlin/06. Views/06.03 EditText with TextWatcher.md b/Android_Development_with_Kotlin/06. Views/06.03 EditText with TextWatcher.md new file mode 100644 index 0000000000..2721396dbf --- /dev/null +++ b/Android_Development_with_Kotlin/06. Views/06.03 EditText with TextWatcher.md @@ -0,0 +1,146 @@ +#
👨‍💻 EditText with TextWatcher 📌
+ +

+ +EditText is used to read input from user. + +A listener could be attached to the EditText to execute an action whenever the text is changed in the EditText View. +In this tutorial, we shall provide you an example Kotlin Android Application to implement a listener, TextWatcher object, for EditText to trigger an action on text change. + +In the following video, we have an EditText, where when user enters text, the listener triggers and reads the text. The text read is displayed in a TextView. + +

+ +To trigger an action for EditText on text change, follow these steps. + +**Step 1**: Add TextWatcher object as listener to reference of the EditText using addTextChangedListener. + +```kotlin +editTextSample.addTextChangedListener(object : TextWatcher { + + override fun afterTextChanged(s: Editable) {} + + override fun beforeTextChanged(s: CharSequence, start: Int, + count: Int, after: Int) { + } + + override fun onTextChanged(s: CharSequence, start: Int, + before: Int, count: Int) { + } +}) +``` + +**Step 2**: Implement your logic in the function onTextChanged(). This method is called to notify you that, withins , thecount characters beginning atstart have just replaced old text that had lengthbefore + +```kotlin +override fun onTextChanged(s: CharSequence, start: Int, + before: Int, count: Int) { + // your code here +} +``` + +**Step 3:** `s: CharSequence` holds the text present in EditText at the moment when text is changed. + +### addTextChangedListener + +addTextChangedListener method could be used to add a TextWatcher object (explanation provided below) to the EditText. + +### TextWatcher + +When TextWatcher object is attached to an Editable, its methods will be called when the text is changed. So, TextWatcher object can be used as a listener for text changes in the EditText. + +### Example 1 -- Listener for EditText on Text Change + +Create an Android Application with Empty Activity and replace the content of layout and Activity files with the following. + +```xml + + + + + + + + + + + + + + +``` + +- MainActivity.kt + +```kotlin +package com.tutorialkart.edittextonchange + +import android.support.v7.app.AppCompatActivity +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import kotlinx.android.synthetic.main.activity_main.* + +class MainActivity : AppCompatActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + editTextSample.addTextChangedListener(object : TextWatcher { + + override fun afterTextChanged(s: Editable) {} + + override fun beforeTextChanged(s: CharSequence, start: Int, + count: Int, after: Int) { + } + + override fun onTextChanged(s: CharSequence, start: Int, + before: Int, count: Int) { + tvSample.setText("Text in EditText : "+s) + } + }) + } +} +``` +Run this Android Application in your Android phone or Emulator. You would get an EditText on the screen. Try entering some text into EditText. When text changes in EditText, onTextChanged() method is called, and we are updating the text of TextView. + +
+ +### Conclusion +In this Kotlin Android Tutorial – EditText on Text Change, we have learnt how to listen on EditText for text changes and implement a code block whenever there is a change to the text in EditText. + +So that is all that you need to get started with the EditText with TextWatcher in Android (Kotlin) , if you have any doubts you can definetly visit the official documentation of [kotlin](https://kotlinlang.org/docs/home.html). + +## HAPPY LEARNING 😎🙌 +
+ +### References-: + +- For preparing these documents official documentation of [kotlin](https://kotlinlang.org/docs/home.html). was referred for maintaining the authenticity of the code and also for making the topics more informative some external sources like [blogs](https://www.tutorialkart.com/kotlin-android/android-edittext-on-text-change/) were referred. + diff --git a/Android_Development_with_Kotlin/09. Dynamic User Interface/09.30 SearchView on ToolBar.md b/Android_Development_with_Kotlin/09. Dynamic User Interface/09.30 SearchView on ToolBar.md new file mode 100644 index 0000000000..ba014eb7a6 --- /dev/null +++ b/Android_Development_with_Kotlin/09. Dynamic User Interface/09.30 SearchView on ToolBar.md @@ -0,0 +1,255 @@ +## Android SearchView on ToolBar + +using the SearchView widget as an item in the app bar is the preferred way to provide search in your app. Like with all items in the app bar, you can define the SearchView to show at all times, only when there is room, or as a collapsible action, which displays the SearchView as an icon initially, then takes up the entire app bar as a search field when the user clicks the icon. + + + +1. Create an activity_main.xml file in layout folder containing ListView. + +## XML + + +# menu.xml +Create a menu.xml file in menu folder and place the following code. This code places the SearchView widget over ToolBar. + +File: menu.xml + + + + + + + + +# Activity class + +File: MainActivity.java + + import android.support.v7.app.AppCompatActivity; + + import android.view.Menu; + + import android.view.MenuInflater; + + import android.view.MenuItem; + + import android.os.Bundle; + + import android.widget.ListView; + + import android.widget.ArrayAdapter; + + import android.widget.SearchView; + + import java.util.ArrayList; + + + + public class MainActivity extends AppCompatActivity { + + + + // List View object + + ListView listView; + + + + // Define array adapter for ListView + + ArrayAdapter adapter; + + + + // Define array List for List View data + + ArrayList mylist; + + + + @Override + + protected void onCreate(Bundle savedInstanceState) + + { + + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_main); + + + + // initialise ListView with id + + listView = findViewById(R.id.listView); + + + + // Add items to Array List + + mylist = new ArrayList<>(); + mylist.add("Apple"); + mylist.add("Banana"); + mylist.add("Pineapple"); + mylist.add("Orange"); + mylist.add("Lychee"); + mylist.add("Gavava"); + mylist.add("Peech"); + mylist.add("Melon"); + mylist.add("Watermelon"); + mylist.add("Papaya") + + + // Set adapter to ListView + + adapter + + = new ArrayAdapter( + + this, + + android.R.layout.simple_list_item_1, + + mylist); + + listView.setAdapter(adapter); + + } + + + + @Override + + public boolean onCreateOptionsMenu(Menu menu) + + { + + // Inflate menu with items using MenuInflator + + MenuInflater inflater = getMenuInflater(); + + inflater.inflate(R.menu.menu, menu); + + + + // Initialise menu item search bar + + // with id and take its object + + MenuItem searchViewItem + + = menu.findItem(R.id.search_bar); + + SearchView searchView + + = MenuItemCompat + + .getActionView(searchViewItem); + + + + // attach setOnQueryTextListener + + // to search view defined above + + searchView.setOnQueryTextListener( + + new SearchView.OnQueryTextListener() { + + + + // Override onQueryTextSubmit method + + // which is call + + // when submitquery is searched + + + + @Override + + public boolean onQueryTextSubmit(String query) + + { + + // If the list contains the search query + + // than filter the adapter + + // using the filter method + + // with the query as its argument + + if (list.contains(query)) { + + adapter.getFilter().filter(query); + + } + + else { + + // Search query not found in List View + + Toast + + .makeText(MainActivity.this, + + "Not found", + + Toast.LENGTH_LONG) + + .show(); + + } + + return false; + + } + + + + // This method is overridden to filter + + // the adapter according to a search query + + // when the user is typing search + + @Override + + public boolean onQueryTextChange(String newText) + + { + + adapter.getFilter().filter(newText); + + return false; + + } + + }); + + + + return super.onCreateOptionsMenu(menu); + + } +} +## Output: + +[![searchview-on-toolbar2.png](https://i.postimg.cc/wBsjvPK7/searchview-on-toolbar2.png)](https://postimg.cc/yJsHpL8H) + +[![searchview-on-toolbar3.png](https://i.postimg.cc/QtQNgTdD/searchview-on-toolbar3.png)](https://postimg.cc/2b5fr3W9) + +[![searchview-on-toolbar4.png](https://i.postimg.cc/50dNF31p/searchview-on-toolbar4.png)](https://postimg.cc/GBK1Wv4s) + + +# Resources: + +[Android SearchView on ToolBar](https://www.javatpoint.com/android-searchview-on-toolbar) + diff --git a/Android_Development_with_Kotlin/12.Fragments/12.1 Fragment Lifecycle in Android.md b/Android_Development_with_Kotlin/12.Fragments/12.1 Fragment Lifecycle in Android.md new file mode 100644 index 0000000000..579dc545f4 --- /dev/null +++ b/Android_Development_with_Kotlin/12.Fragments/12.1 Fragment Lifecycle in Android.md @@ -0,0 +1,204 @@ +Android Kotlin: 12.1 Fragment Lifecycle in Android #5217 + + +## **Definitions:** + + +### **Fragment** + +In Android, the fragment is the part of Activity which represents a portion of User Interface(UI) on the screen. Each fragment has it’s own lifecycle but due to the connection with the Activity it belongs to, the fragment lifecycle is infulenced by the activity’s lifecycle. + + + +### **Fragment Lifecycle** + +The lifecycle of a fragment represents all the states a fragment undergoes from it's attachment to an activity to it's deattachment from the activity. + + + ______________________________________________________________________________________________________________________________________________________________________________ + + +## **States/Methods of the Android Fragment Lifecycle :** + + +### **1) onAttach** + +The very first method to be called when the fragment has been associated with the activity. This method executes only once during the lifetime of a fragment. + +Below is the example code of onAttach() method. + + + override fun onAttach(activity: Activity) { + super.onAttach(activity) + // add code when fragment instance is attached to activity + } + + + + + +### **2) onCreate()** + +This method initializes the fragment by adding all the required attributes and components. + +Below is the example code of onCreate() method. + + + override fun onCreate(saveInstanceState: Bundle) { + super.onCreate(saveInstanceState) + // add your code here which executes when fragment's instance initializes + } + + + +### **3) onCreateView()** + +System calls this method to create the user interface of the fragment. The root of the fragment’s layout is returned as the View component by this method to draw the UI. + +Below is the example code of onCreateView() method. + + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) : View { + + val view = inflater.inflate(R.layout.fragment, container, false) + // add code here which executes when the views are created + return view + } + + + + +### **4) onViewCreated()** + +System calls this method after the views have been initialised. The data to their corresponding views can be binded in this state. + +Below is the example code of onViewCreated() method. + + + override fun onViewCreated(view: View, saveInstanceState: Bundle) { + super.onViewCreated(view, saveInstanceState) + // add your code that executes after the creation of layout views + } + +### **5) onActivityCreated()** + +It indicates that the activity has been created in which the fragment exists. View hierarchy of the fragment also instantiated before this function call. + +Below is the example code of onActivityCreated() method. + + + override fun onActivityCreated(saveInstanceState: Bundle) { + super.onActivityCreated(savedInstanceState) + // add your code that executes after the host activity is created + } + + +### **6) onStart()** + +The system invokes this method to make the fragment visible on the user’s device. + +Below is the example code of onStart() method. + + + override fun onStart() { + super.onStart() + // add your code here which executes when the Fragment gets visible. + } + + +### **7) onResume()** + +This method is called to make the visible fragment interactive. In simple words, the fragment gets focused to interact with users. + +Below is the example code of onResume() method. + + + override fun onResume() { + super.onResume() + // add your code here which executes when the Fragment gets focused and interactable. + } + +### **8) onPause()** + +The counter method of onResume() where the fragment loses it's focus and is uninteractive with the user. + +Below is the example code of onPause() method. + + + override fun onPause() { + super.onPause() + // add your code here which executes when the Fragment loses it's focus and is no longer interactive. + } + + + +### **9) onStop()** + +Method to terminate the visibility of fragment from the user’s screen. + +Below is the example code of onStop() method. + + + override fun onStop() { + super.onStop() + // add your code here which executes when the Fragment is no longer visible. + } + +### **10) onDestroyView()** + +System calls this method to clean up all kinds of resources as well as view hierarchy associated with the fragment. + +Below is the example code of onDestroyView() method. + + + override fun onDestroyView() { + super.onDestroyView() + // add your code here which executes when the view's and other related resources created in onCreateView() method are removed + } + +### **11) onDestroy()** + +It is called to perform the final clean up of fragment’s state and its lifecycle. + +Below is the example code of onDestroy() method. + + + + override fun onDestroy() { + super.onDestroy() + // add your code here which executes when the final clean up for the Fragment's state is needed. + } + + +### **12) onDetach()** + +The system executes this method to disassociate the fragment from its host activity. + +Below is the example code of onDetach() method. + + + override fun onDetach() { + super.onDetach() + // add your code here which executes when fragment has been disassociated from its hosting activity + } + + +______________________________________________________________________________________________________________________________________________________________________________ + + + Below is the pictorial representation of the Android Fragment Lifecycle : + + + + + + + + + + + ## Author + + + [Amaan Ur Rahman](https://github.com/amaan118921) + diff --git a/Android_Development_with_Kotlin/12.Fragments/12.2 Jetpack Navigation Components.md b/Android_Development_with_Kotlin/12.Fragments/12.2 Jetpack Navigation Components.md new file mode 100644 index 0000000000..bdf3c6209b --- /dev/null +++ b/Android_Development_with_Kotlin/12.Fragments/12.2 Jetpack Navigation Components.md @@ -0,0 +1,513 @@ +# Android Kotlin - "Jetpack Navigation Components in Android" +(This Documentation is a part of "Android Development in Kotlin" -> 12. Fragments -> 12.2 Jetpack Navigation Components) +
+ +> **Welcome to the Documentation of "Jetpack Navigation Components in Android".** +
+ +

+ +

+[ Source of this picture: MindOrks ] + +
+ +### Table of Contents: + +* [What is Jetpack](#What-is-Jetpack) +* [What is Navigtion](#What-is-Navigtion) +* [Benefits of Navigation Component](#Benefits-of-Navigation-Component) +* [Three key parts of Navigation Component](#Three-key-parts-of-Navigation-Component) +* [Implementation](#Implementation) +
+
+ + + + + +## What is Jetpack + Android Jetpack provides a set of tools, libraries and architectural guidelines, which help us to build quality Android applications in a faster and easy way. To use it we have to add Androidx namespace into our project, which comprises of Android Jetpack Libraries. Navigation component is the latest library introduced by Android Jetpack. + +
+ +## What is Navigtion +Basically, Navigation refers to the interactions that allow users to navigate across, into, and back out from the different pieces of content within your app. Its a a collection of libraries, tools, and plugins for uniform and smooth navigation and without navigation, we have to write a big manual code to move from one screen to another screen that creates complex navigation paths. + +
+ +## Benefits of Navigation Component +* Handling fragment transactions. +* Testing is much easier. +* Handles back and forth navigation by default +* It provides Implementation and handling of deep linking. +* Default behaviors for animations and transitions +* Including Navigation UI patterns, such as navigation drawers and bottom navigation, with minimal additional work. +* Passing arguments is much safer. +* `Safe Args` – a Gradle plugin that provides type safety when navigating and passing data between destinations. +

+ + +Note : If you want to use Navigation with Android Studio, you must use Android Studio 3.3 or higher.

+ + +## Three key parts of Navigation Component + +The Navigation Component consists of three key parts, working together in harmony. They are:
+ +1. Navigation Graph (New XML resource) - This is a resource that contains all navigation-related information in one centralized location. This includes all the places in your app, known as destinations, and possible paths a user could take through your app.
+[ Source of this picture: DhiWise ] +

+ +

+ + +2. NavHostFragment (Layout XML view) - This is a special widget you add to your layout. It displays different destinations from your Navigation Graph.
+[ Source of this picture: DhiWise ] +

+ +

+ + + +3. NavController (Kotlin/Java object) - This is an object that keeps track of the current position within the navigation graph. It orchestrates swapping destination content in the NavHostFragment as you move through a navigation graph. +When you navigate, you'll use the NavController object, telling it where you want to go or what path you want to take in your Navigation Graph. The NavController will then show the appropriate destination in the NavHostFragment.
+[ Source of this picture: stackoverflow ] + +

+ +

+ +
+
+ +## Implementation +[ Source of this Project: camposha.info ] +
+ + Step 1: Create Project
+Start by creating an empty Android Studio project. + + Step 2: Dependencies
+In your app/build.gradle add the following Jetpack Navigation Component Libraries: + +``` + // navigation component + implementation "androidx.navigation:navigation-fragment-ktx:2.3.2" + implementation "androidx.navigation:navigation-ui-ktx:2.3.2" + +``` +
+ + Step 3: Enable ViewBinding and Java8
+Still in the app/build.gradle, but under the android{} closure, enable viewBinding and Java8 as follows: + +``` + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + buildFeatures { + viewBinding true + } +``` +
+ + Step 4: Create Transition Animations
+Create a folder known as anim under the res directory and inside it add transition animations.
+slide_in_right + +``` + + + + +``` + +slide_out_left.xml + +``` + + + + +``` +
+ + Step 5: Create a Navigation Graph
+Under the res create a folder known as navigation and inside it create a navigation graph as follows:
+nav_graph.xml + +``` + + + + + + + + + + + + + + + + + + + + + + +``` +
+ + Step 6: Create Options Menu
+We will use Options Menu to navigate our fragments, therefore create the following two: + +(a). options_menu.xml + +``` + + + + + + + +``` +
+ +(b). navigation_menu.xml + +``` + + + + + + + +``` +
+ + Step 7: Design Layouts
+We will have the following layouts:
+ +1. MainActivity layout – activity_main.xml +2. Home Fragment Layout – fragment_home.xml +3. Login Fragment Layout – fragment_login.xml +4. Search Fragment Layout – fragment_search.xml +5. Settings Fragment Layout – fragment_settings.xml +6. Terms Fragment Layout – fragment_terms.xml +7. Welcome Fragment Layout – fragment_welcome.xml
+Here is the code for the main activity layout:
+activity_main.xml + +``` + + + + + + + + + + + + + + +``` +
+ + Step 8: Create Fragments
+We will have the following fragments:
+ +1. HomeFragment +2. LoginFragment +3. SearchFragment +4. SettingsFragment +5. TermsFragment +6. WelcomeFragment
+ +HomeFragment.kt
+ +Here is the code for this fragment:
+ +``` +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.navigation.fragment.findNavController +import xyz.teamgravity.navigationcomponent.databinding.FragmentHomeBinding + +class HomeFragment : Fragment() { + + private var _binding: FragmentHomeBinding? = null + private val binding get() = _binding!! + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + _binding = FragmentHomeBinding.inflate(inflater, container, false) + + return binding.root + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + + // login button + binding.loginB.setOnClickListener { + val action = HomeFragmentDirections.actionHomeFragmentToLoginFragment() + findNavController().navigate(action) + } + } + + override fun onDestroyView() { + super.onDestroyView() + _binding = null + } +} +``` +
+ + Step 9: Create MainActivity
+Here is the code for the MainActivity:
+MainActivity.kt + +``` +import android.os.Bundle +import android.view.Menu +import android.view.MenuItem +import android.view.View +import androidx.appcompat.app.AppCompatActivity +import androidx.navigation.NavController +import androidx.navigation.fragment.NavHostFragment +import androidx.navigation.fragment.findNavController +import androidx.navigation.ui.* +import xyz.teamgravity.navigationcomponent.NavGraphDirections +import xyz.teamgravity.navigationcomponent.R +import xyz.teamgravity.navigationcomponent.databinding.ActivityMainBinding + +class MainActivity : AppCompatActivity() { + + private lateinit var binding: ActivityMainBinding + + private lateinit var navController: NavController + private lateinit var appBarConfiguration: AppBarConfiguration + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityMainBinding.inflate(layoutInflater) + binding.apply { + setContentView(root) + + // find nav controller + val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment + navController = navHostFragment.findNavController() + + // hide back button from top level fragments + appBarConfiguration = AppBarConfiguration(setOf(R.id.homeFragment, R.id.searchFragment), binding.drawerLayout) + + setSupportActionBar(toolbar) + setupActionBarWithNavController(navController, appBarConfiguration) + + bottomNavigation.setupWithNavController(navController) + navigationDrawer.setupWithNavController(navController) + + // hide bottom navigation + navController.addOnDestinationChangedListener { _, destination, _ -> + when (destination.id) { + R.id.termsFragment, R.id.settingsFragment -> + bottomNavigation.visibility = View.GONE + else -> + bottomNavigation.visibility = View.VISIBLE + } + } + } + } + + // in order to respond back button in toolbar from fragment + override fun onSupportNavigateUp(): Boolean { + return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() + } + + override fun onCreateOptionsMenu(menu: Menu?): Boolean { + menuInflater.inflate(R.menu.options_menu, menu) + return true + } + + // to navigate fragments in menu with nav controller + override fun onOptionsItemSelected(item: MenuItem): Boolean { + return if (item.itemId == R.id.termsAndConditions) { + val action = NavGraphDirections.actionGlobalTermsFragment() + navController.navigate(action) + true + } else { + item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item) + } + } +} +``` +
+ + Run
+Below the snapshots of Output given: +
+[ Source of this picture: camposha.info ] +
+ +

+ +

+
+ +

+ +

+
+ +

+ +

+ +This nice Implementation of "Jetpack Navigation Components" is by camposha.info . + +
+ +For more and deep information about Jetpack Navigation Components , Refers to the official Android doumentation developer.android.com + +
+Was this Documentation helpful? If yes give a star to this Repository. + +#### Authors +- [Ayush Mishra](https://github.com/ayush-sleeping) + +