Search code examples
android-studiolive-templatesandroid-studio-2.1

Live Template in Android Studio which centers variable and changes line length based on variable


This is somewhat of a mild OCD and obsessive optimizing question, which will probably only be of use for me.

I want to create a Live Template in Android Studio, which looks like this:

// -------------------------------------------------- \\
// -------------------------$variable$------------------------- \\
// -------------------------------------------------- \\

I want the variable bit of text to be centered, and the second line to be just as long as the other two, all done automatically. An example:

// -------------------------------------------------- \\
// ----------------- Example Title ------------------ \\
// -------------------------------------------------- \\

Is this possible with the Live Templates in Android Studio, and if so, how would that work?


Solution

  • Do like on image(LiveTemplateSettings). Just copy and paste:

    skipIfDefined   VAR4    groovyScript("new String(new char[90]).replace('\\0','-')")
                    VAR1    groovyScript("String x=\"yazGitsin\"; x=_1.size()>2?_1:x;return x;",VAR1)
    skipIfDefined   VAR2    groovyScript("String slash = new String(new char[90]).replace('\\0','-');int lenght = slash.length();int leftSize = (lenght - _1.length()) / 2;int temp=lenght-leftSize-_1.length();int rightSize=temp+(temp+leftSize+_1.length())%2;return slash.substring(0,leftSize);",VAR1) 
    skipIfDefined   VAR3    groovyScript("String slash = new String(new char[90]).replace('\\0','-');int lenght = slash.length();int leftSize = (lenght - _1.length()) / 2;int temp=lenght-leftSize-_1.length();int rightSize=temp+(temp+leftSize+_1.length())%2;return slash.substring(0,rightSize);",VAR1) 
    
    //-$VAR4$-\\
    //$VAR2$ $VAR1$ $VAR3$\\
    //-$VAR4$-\\
    $END$
    

    when you are writing "lll" on intellij popup will show, enter it and write what you want. And if you want how is it working or become more strong on live template: https://www.jetbrains.com/help/phpstorm/2016.2/live-template-variables.html