How to create a new composable function in Android Studio?
Asked Answered
H

2

8

Each time, I need to create a composable function, I do:

Right click on a package -> New -> Kotlin Class/File

And I end up with this:

class MyClass {}

Now I have to do three changes manually:

  1. Add @Composable annotation
  2. Change class with fun
  3. Create the constructor

And this is really annoying. But this is the result:

@Composable
fun MyClass(
    //Add arguments
) {
    //Add logic
}

How can I do this operation quicker? Is there any shortcut in Android Studio? I couldn't find anything in the menu.

Hjerpe answered 6/9, 2022 at 10:43 Comment(0)
A
9

You can define you own template for this:

  • Open the Settings
  • Go to Editor > File and Code Templates
  • Click the + icon to add a new template
  • set the Name to My Composable template or whatever you like
  • set the Extension to kt
  • Copy and paste the code block from your question into the large empty text box on the right (directly under File name)
  • Click OK

Then, instead of New > Kotlin Class you can click New > My Composable template (or whatever you named it), and you start without the extra manual steps.

Admittedly answered 6/9, 2022 at 11:37 Comment(0)
K
1

below template would suffice

#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME}

#end #parse("File Header.java")

import androidx.compose.runtime.Composable

@Composable #set($capitalizedFilename = $NAME.substring(0,1).toUpperCase() + $NAME.substring(1)) fun $capitalizedFilename() {

}
Kahle answered 6/4 at 13:25 Comment(1)
Much better than the accepted answer as this automatically gets the compose fun name, package namespace and imports.Housman

© 2022 - 2024 — McMap. All rights reserved.