androidandroid-studiokotlinlive-templates

How to create a kotlin live template for newInstance Fragments using Android studio


I'm searching for a way to create a new Kotlin live code template so that whenever I type newIns.... it and hit tab it will be able to print the following as a live template choice:

companion object {
    fun newInstance(b: Bundle): DetailsFragment {
        val frag = DetailsFragment()
        frag.arguments = b
        return frag
    }
}

In Java, it was done the same way and there is already a "newInstance" abbreviation and a live template exists in Android Studio. I want the same thing for Kotlin. Let me show you a photo :

enter image description here

Notice that, Java Android already has newInstance template. I want this for Kotlin. Here is what I have so far:

enter image description here

and the template code I have so far looks like this:

companion object { 
    fun newInstance($args$:Bundle):$fragment$ {
        $nullChecks$
        android.os.Bundle args = Bundle();
        $addArgs$
        $fragment$ fragment = $fragment$();
        fragment.setArguments(args);
        return fragment;
    }
}

but when I exit the settings and in Kotlin type the first few words of the abbreviation and hit tab or ctrl + spacebar on mac nothing happens. I guess I have the syntax wrong, I'm not sure. Anyone of suggestions?


Solution

  • Step 1:

    Go to Live Templates section in Android Studio.

    For Windows:

    File > Settings > Editor > Live Templates

    For Mac:

    Android Studio > Preferences > Editor > Live Templates

    Step 2:

    Select Kotlin template group. Then tap on + present at the top-right corner of the popup. Select Live Template.

    Step 3:

    Now you can add your live template. Check at the bottom of the popup.

    Add abbreviation: newInstance

    Add description: Creates an instance of the fragment with arguments

    Add template text:

    companion object {
        fun newInstance(args: Bundle): $fragment$ {
            val fragment = $fragment$()
            fragment.arguments = args
            return fragment
        }
    }
    

    Add applicable context. Tap on Define. Select Kotlin from the list.

    Select Reformat according to style

    Step 4:

    Tap on Edit Variables below the description.

    Now tap on Expression for the variable name fragment. Tap on down arrow. You can see a list of expressions. From there select kotlinClassName().

    Tap on OK of the Edit Templates Variable

    Now tap on Apply and OK of the Live Templates.

    To check type newInstance in a Fragment written in Kotlin.