This article has participated in the third “topic writing” track of the Denver Creators Training Camp. For details, check out: Digg Project | Creators Training Camp third is ongoing, “write” to make a personal impact.

🌻 generic + reflection

When we create an Activity

  1. SetContentView (R.Layout..)
  2. If you use a ViewModel, you also have to create a ViewModel for each Activity.

If you have too many activities in your project, you’re writing a lot of template code. With Java’s generics mechanism, we can encapsulate this logic in BaseAct.

1.1 the sample

First create BaseAct

abstract class BaseAct<B : ViewDataBinding, VM : ViewModel> : AppCompatActivity() {
    private var mBinding: B? = null
    private lateinit var mModel: VM
    abstract val layoutId: Int
    abstract fun doBusiness(savedInstanceState: Bundle?).
    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        / / create the View
        setContentView(createViewBinding().root)
        / / create the ViewModel
        createViewModel()
        doBusiness(savedInstanceState)
    }
    
    fun getB(a): B {
        return mBinding!!
    }
    
    fun getVM(a): VM {
        return mModel
    }

    private fun createViewBinding(a): B {
        mBinding = DataBindingUtil.inflate(LayoutInflater.from(this), layoutId, null.false) mBinding!! .lifecycleOwner =this
        return mBinding!!
    }

    private fun createViewModel(a) {
        val type = javaClass.genericSuperclass!! as ParameterizedType
        val argsType = type.actualTypeArguments
        val modelClass: Class<VM> = argsType[1] as Class<VM>
        val model = ViewModelProvider(this).get(modelClass)
        mModel = model
    }

    override fun onDestroy(a) {
        super.onDestroy() mBinding? .unbind() mBinding =null}}Copy the code

When you create a LoginAct, you can write this

// Declare generic classes
class LoginAct : BaseAct<LoginActBinding, LoginActViewModel>() {
    override val layoutId: Int = R.layout.login_act

    override fun doBusiness(savedInstanceState: Bundle?). {
        // Logical processing
        getVm() // Get LoginActViewModel}}class LoginActViewModel : ViewModel() {}Copy the code

🍁 Generate multiple files at once

LoginAct creation above. We usually have to do the following steps

  1. Create an XML layout
  2. New a Kotlin Class/File to create LoginViewModel
  3. New a Kotlin Class/File to create LoginAct
  4. LoginAct inherits BaseAct and overrides the method

You can simplify this step with the templates template.

2.1 Before AS version 4.1

The FreeMarker template engine is used

2.1.1 Place the template in the corresponding directory

  1. New Foldermvvm_templatesPut it in the directory ** Android Studio\plugins\ Android \lib\templates\activities **
  2. Place the following files inmvvm_templatesIn the folder

2.1.2 Introduction to Template Files

Mvvm_templates | | - root / / file - SRC | - app_package | -- xx. Kt / / expectations generated kt file | -- xx. Java / / expectations generated Java file | -... | - | res / / resource template - xx. XML. FTL / / expectations generated XML | -... | - globals. XML. FTL | -- recipe. XML. The FTL / / manage all files statement | -- template. XML/console/templateCopy the code

2.1.3 Usage

  • The FTL above describes the parameters and instructions to execute the template
  • After as starts, Android Studio will parse”/templates“Folder contents to” **New ->** “Menu interface add template name, when clicking the corresponding template name, Android Studio will read”template.xml“Content, build UI, etc.

I have upgraded as, so I cannot cut my own configuration page diagram. The principle is the same. You can choose the options configured in your template from the diagram above.

  1. Where to download my mvVM_templates template

This is my own configuration, you can take reference to modify.

2.2 As version 4.1 Later

Starting with Android Studio 4.1, Google discontinued support for custom FreeMarker templates. This feature is very useful to me, so I found another solution 1 and solution 2 on Github

Many people respond to Google’s question tracker, but are still waiting for official support.

Three 🌵 generate one file at a time

Edit File Templates to create single XML, single files, and File class Templates

3.1 Creating an XML layout

The steps are tedious and require a few clicks. The resulting layout file has only one root layout.

The following template layout simplifies the above steps and allows you to set up some common scaffolding layouts.

3.2 Creating an XML template layout

3.2.1 Configuring a Template

  1. Edit template
  2. Create a file
  3. Define template names
  4. Defining file suffixes
  5. Copy your template layout in
  6. complete

3.2.2 Using a Template

The template you just configured will be displayed here, and the layout will be generated when clicked.

The configuration layout is automatically filled in, and you can define many different templates for different scenarios.

3.3 Creating a KT File Template

The steps are the same as above to create the XML template, except for the file name extension. There is an extra File Header. Create it as follows.

3.4 Creating a File Header

🌷 Quick output of a single file

Live Templates in the AS Settings

4.1 the sample

If I want the red image to be centered, I have to add four lines of constraint properties, which are often written in our development. Wouldn’t it save time if I typed cc in the XML and hit Enter to generate these four lines of code?

4.2 configuration

Group management is recommended.

  • Shortcuts in XML create a separate group.
  • Create a separate group in kotlin shortcuts.

4.3 🔥 use

I set up

  • Cc displays four constraint attributes
  • Tt displayapp:layout_constraintTop_toTopOf="parent"
  • Similarly, in Kotlin, in Java, things like log printing, if judgments, initializing variables, more usage scenarios, etc.

4.4 🔥 My own template

As will generate our configuration template in this path: C:\Users\userName\AppData\Roaming\Google\AndroidStudio4.1\templates

🌿AS common plug-ins

5.1 WiFi Connection mobile phone debugging

5.2 Translation into English

5.3 other

  • Alibaba Java Coding Guidelines Alibaba Java Coding Guidelines
  • CodeGlance can preview the code structure on the right for quick positioning
  • Database Navigator Database debugging