Search code examples
android-studiointellij-ideaidelive-templates

Intellij Idea Live Template to create field and method at same time


How to create field variable automatically when I create method used that field. I've create template like this:

void $METHOD_NAME$() {
    $FIELD_NAME$ = true;
}

when I type field name (e.g. mState) in method will create field as:

private boolean mState = false;

Hope someone help. Sorry my bad.


Solution

  • Given the screenshot of your template, you can also create a field with the following live template:

    private boolean $param$ = false;
    
    @Override
    public void onBackPressed() {
      if ($param$) super.onBackPressed();
      android.widget.Toast.makeText(this, "$message$",
        android.widget.Toast.LENGTH_SHORT).show();
      $param$ = true;
      final Handler handler = new Handler();
      handler.postDelayed(new Runnable() {
        @Override
        public void run() {
          $param$ = false;
        }
      }, 100);
    }
    

    Where $param$ and $message$ are regular variables without anything special.

    However, like I said in the comment on your question, I suggest to split it up in several smaller templates. Consider to split it up in: field + method with just:

    private boolean $param$ = false;    
    
    @Override
    public void onBackPressed() {
      if ($param$) super.onBackPressed();
      $param$ = true;
    }
    

    Then create a template for the message:

    android.widget.Toast.makeText(this, "$message$", android.widget.Toast.LENGTH_SHORT).show();
    

    And last but not least, create a template for the postDelayed:

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            $END$
        }
    }, $delay$);
    

    Note: the $delay$ as a bonus you can even give it a default value or create a list of predefined values for ease of use.

    Note2: Instead of $param$ = false; I've replaced it with $END$. This will position your cursor here once you've selected the delay. Now you can type mState = false manually here, or whatever code you need in the context at that moment. This makes the template much more flexible and easier to use.

    PS. I suppose you want to call super.onBackPressed() only when the value is false (on the first invocation). In that case use if (!$param$) instead.

    // Update:

    In order to group the newly added field with the other fields and not halfway somewhere in your class between other methods, rearrange the code via the menu with: Code -> rearrange code. To customise this, check your arrangement settings under: settings -> code style -> <language> -> arrangement