连接网络后关闭小吃店

时间:2019-11-08 10:09:45

标签: android kotlin android-snackbar

不了解为什么snackbar中的else无法正常工作,为什么不解雇我的snackbar

private fun showNetworkMessage(isConnected: Boolean) {
    val snackbar = Snackbar.make(
        findViewById(R.id.coordinatorLayout),
        this.getText(R.string.warning_no_internet_connection), Snackbar.LENGTH_INDEFINITE
    )
    val snackBarLayout = snackbar.view as Snackbar.SnackbarLayout
    for (i in 0 until snackBarLayout.childCount) {
        val parent = snackBarLayout.getChildAt(i)
        if (parent is LinearLayout) {
            parent.rotation = 180f
            break
        }
    }
    snackbar.view.setOnTouchListener { _, _ ->
        snackbar.dismiss()
        true
    }
    if (!isConnected) {
        snackbar.show()
    } else {
        snackbar.dismiss()
    }
}

3 个答案:

答案 0 :(得分:1)

尝试将Snackbar的声明移出函数,然后重试。

答案 1 :(得分:1)

声明全局变量,

  private fun showNetworkMessage(isConnected: Boolean) {
        if (snackbar == null) {
            snackbar= Snackbar.make(
                    findViewById(R.id.coordinatorLayout),
                    this.getText(R.string.warning_no_internet_connection), Snackbar.LENGTH_INDEFINITE
            )    
        }

功能更改

--version

答案 2 :(得分:1)

保持全局snackbar

var snackbar: Snackbar? = null

private fun showNetworkMessage() {
   snackbar = Snackbar.make(
        findViewById(R.id.coordinatorLayout),
        this.getText(R.string.warning_no_internet_connection), Snackbar.LENGTH_INDEFINITE
    )
    val snackBarLayout = snackbar.view as Snackbar.SnackbarLayout
    for (i in 0 until snackBarLayout.childCount) {
        val parent = snackBarLayout.getChildAt(i)
        if (parent is LinearLayout) {
            parent.rotation = 180f
            break
        }
    }
    snackbar.view.setOnTouchListener { _, _ ->
        snackbar.dismiss()
        true
    }
    snackbar.show()
}

private fun dismissNetworkMessage() {
    snackbar?.dismiss()
}

private fun showNetworkMessage(isConnected: Boolean) {
    if (!isConnected) {
        showNetworkMessage()
    } else {
        dismissNetworkMessage()
    }
}