0x00 前言
最近在整理项目中的代码,由于项目的代码比较久远,某些类的代码量相对比较庞大,新人在接手维护这个类的时候熟悉起来比较困难,仅仅依靠文档和注释理解起来也比较吃力。后来想起IntelliJ IDEA中有Custom code folding regions的操作方式,可以将代码块归纳折叠为标签的形式,让代码看起来规整了很多。
形成类似如下的效果:
在Structure导航中看起来也比较清晰
0x01 操作实现
class MainActivity : AppCompatActivity() {
//<editor-fold desc="* 1. 这种成员变量">
private lateinit var appBarConfiguration: AppBarConfiguration
//</editor-fold>
//<editor-fold desc="* 2. 主要的函数方法">
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
}
//</editor-fold>
//<editor-fold desc="* 3. 辅助的函数方法">
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
//</editor-fold>
}
选择好需要折叠的代码片段,然后使用快捷键或者在菜单栏中选择如下action
在弹出的菜单中选择,<editor-fold..>
或者region..endregion
中的任意一个都可以。
对于以上两者的区别,官方给出的解释是
As you can see there are two custom folding items: “<editor-fold…>” for NetBeans-like style and “region…endregion” for VisualStudio style
添加好对应的折叠注释
就可以实现像折叠展开studio的其他代码块一样的效果,进行展开收纳