Kotlin : Android’s future is here – Part 3

Overview

Activity, Fragment & Dialog Fragment

This blog is aimed to learn how to open dialog fragment and fragment from activity.

Opening activity from activity

I’ll explain this procedure using splash screen demo.

Handler is used to perform a task after specific period of time.
I have used startActivity( ) method to start another activity (MainActivity).

Opening dialog fragment from activity

First of all create a class for dialog fragment and extend it.

Now, create object of this class in MainActivity and call show( ) method to show the dialog fragment.

Here, bt is a button which opens the dialog fragment when clicked.

Notes:-

  1. Here, lambda function is used with setOnClickListener( ) (written inside { }). This is the correct way to call anonymous method instead of calling it via an inner class which is used in java.
  2. getters and setters aren’t used. Instead of these, properties are used. For eg. fragmentManager instead of getFragmentManager( ).

Opening fragment from activity

First of all, take a frame in activity’s layout.

Now, create a class for fragment and extend it.

Now, from activity, begin fragment transaction and replace the frame with the fragment.

Finally, commit the transaction.

Note:-
Here, (?.) is used multiple times in same line. This is called chaining. If any (?.) operator returns null then the complete expression will be null. This is one of the disadvantages of Kotlin.

Conclusion

This shows how adaptable Kotlin is for Android Developers. It’s almost similar to java with just a few changes.

mm

Sumeet Rukeja Android Developer

I am an Android Developer at Yudiz Solutions Pvt. Ltd. - a leading Mobile App Development Company. I am passionate about developing android apps and to learn more and more about the deep sea of Android.

Comments are closed.

Top