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).
Handler().postDelayed({ val i = Intent(this, MainActivity::class.java) startActivity(i) finish() }, 3000)
Opening dialog fragment from activity
First of all create a class for dialog fragment and extend it.
class DialogFrag : DialogFragment() { private var text: TextView? = null private var array = ArrayList<String>() private var rv: RecyclerView? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View { var view: View? = inflater?.inflate(R.layout.activity_main2, container, false) return view!! } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NORMAL, R.style.AppTheme) } }
Now, create object of this class in MainActivity and call show( ) method to show the dialog fragment.
bt?.setOnClickListener() { view -> DialogFrag().show(fragmentManager, "dialFrag") }
Here, bt is a button which opens the dialog fragment when clicked.
Notes:-
- 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.
- 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.
<FrameLayout android:id="@+id/frame" android:layout_width="match_parent" android:layout_height="match_parent"/>
Now, create a class for fragment and extend it.
class Fragment1 : Fragment() { override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view: View? = inflater?.inflate(R.layout.activity_main2, container, false) return view } }
Now, from activity, begin fragment transaction and replace the frame with the fragment.
fragmentManager.beginTransaction()?.replace(R.id.frame, Fragment1() as Fragment)?.addToBackStack("frag")?.commit() //chaining
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.