在 Kotlin 中使用按钮展开和折叠折叠工具栏

Expand and collapse a colapsingToolBar with a button in Kotlin

我想在 android studio 中展开和折叠 CollapsingToolBar 当我点击一个按钮时。

我希望它默认折叠。我做错了什么,我不知道是什么,谢谢你的帮助。

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    //maybe this doesnt go here, im trying to make it collapse by default
    var start = appbar.setExpanded(false)

    button.setOnClickListener {
        if(start == appbar.setExpanded(false)){
            start = appbar.setExpanded(true)

        }else{
            start = appbar.setExpanded(false)
        }

    }

}

试试这个:

class MainActivity : AppCompatActivity() {

    private var isAppbarExpanded = false

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    button.setOnClickListener {
        if(!isAppbarExpanded){
            appbar.setExpanded(true)
            isAppbarExpanded = true
        }else{
            appbar.setExpanded(false)
            isAppbarExpanded = false
        }

    }

}