Android Studio の 自定义代码块折叠

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的其他代码块一样的效果,进行展开收纳
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值