Android Studio の 自定义代码块折叠

0x00 前言

最近在整理项目中的代码,由于项目的代码比较久远,某些类的代码量相对比较庞大,新人在接手维护这个类的时候熟悉起来比较困难,仅仅依靠文档和注释理解起来也比较吃力。后来想起IntelliJ IDEA中有Custom code folding regions的操作方式,可以将代码块归纳折叠为标签的形式,让代码看起来规整了很多。

形成类似如下的效果:
Android Studio の 自定义代码块折叠_第1张图片
在Structure导航中看起来也比较清晰
Android Studio の 自定义代码块折叠_第2张图片

0x01 操作实现

class MainActivity : AppCompatActivity() {

    //
    private lateinit var appBarConfiguration: AppBarConfiguration
    //

    //
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        val fab: FloatingActionButton = findViewById(R.id.fab)
        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        val navView: NavigationView = findViewById(R.id.nav_view)
        val navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        appBarConfiguration = AppBarConfiguration(setOf(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow), drawerLayout)
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        return true
    }
    //

    //
    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
    //
}

选择好需要折叠的代码片段,然后使用快捷键或者在菜单栏中选择如下action
Android Studio の 自定义代码块折叠_第3张图片
在弹出的菜单中选择,或者region..endregion中的任意一个都可以。
Android Studio の 自定义代码块折叠_第4张图片
对于以上两者的区别,官方给出的解释是

As you can see there are two custom folding items: “” for NetBeans-like style and “region…endregion” for VisualStudio style

添加好对应的折叠注释
Android Studio の 自定义代码块折叠_第5张图片
就可以实现像折叠展开studio的其他代码块一样的效果,进行展开收纳
在这里插入图片描述

你可能感兴趣的:(善用佳软)