Posts

Showing posts with the label Fragment

Listen to Back Button Clicks in Fragment

Listening to the back button click event inside the fragments, comprised of a painful implementation of the interfaces and the onBackPressed method calls in both Activity and Fragment, prior to the introduction of the OnBackPressedDispatcher . But now, inside a Fragment, the back button behaviour can be controlled by listening to the callback returned by the OnBackPressedDispatcher . This callback listener is implemented inside the  onCreate overridden method. override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Listen to Back button clicks val callback = requireActivity().onBackPressedDispatcher.addCallback(this) { // Handle the back button event } } Use onBackPressedDispatcher method to get the OnBackPressedDispatcher and add the callback using the addCallback method. This callback method takes a lifecycle owner. Handle the back button events whenever the callback gets triggered. The same implementation can be d...

Add Options Menu to Activity and Fragment

Image
Options Menu contains a set of primary menu items that are accessible to the user. In this article, we will take a look at how to implement the options menu in an Android Activity or a Fragment. Right click on the res directory in Android Studio and select Android Resource File option. It opens the Resource File creation modal where we need to enter the file name and select Resource Type as Menu. Clicking on OK button creates main_menu.xml under menu directory. Now add the following items to the XML file. <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/search" android:icon="@drawable/ic_search_white" android:orderInCategory="100" android:title="@string/action_title_search" app:actionViewClass="androidx.appcompat.widget.SearchView" app:showAsAction="ifRoo...