Android kotlin butterknife 视图可见性

Android kotlin butterknife view visibility

我试图在 android 中使用 ButterKnife 和 Kotlin

设置视图的可见性

我在 butterknife 中得到的 id 是这样的:

@BindView(R.id.progress)
lateinit var progress: ProgressBar

可以在 Java 中设置可见性,例如:(我们知道)

progress.setVisibility(View.VISIBLE);
progress.setVisibility(View.GONE);

我试过了:progress.visibility to .... ?

在 kotlin 中使用 ButterKnife 会怎么样?

试试

progress.visibility= View.VISIBLE 
progress.visibility= View.GONE 

备注

你应该使用 kotlinx.android.synthetic.

Every Android developer knows well the findViewById() function. It is, without a doubt, a source of potential bugs and nasty code which is hard to read and support. While there are several libraries available that provide solutions to this problem, those libraries require annotating fields for each exposed View.

The Kotlin Android Extensions plugin allows us to obtain the same experience we have with some of these libraries, without having to add any extra code.

例子

import kotlinx.android.synthetic.main.activity_main.*

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

            // Instead of findViewById<ProgressBar>(R.id.progress)
             progress.visibility= View.GONE 
        }
    }

您可以在 Kotlin 中使用相同的设置器:

progress.setVisibility(View.VISIBLE)

您也可以改用 属性 访问语法,其作用完全相同:

progress.visibility = View.VISIBLE

至于你问题的最后一部分,如果你想这样写:

progress.visibility to View.VISIBLE

然后所做的就是创建一个 Pair,它从未被使用过,只是被丢弃了——它等同于:

Pair(progress.visibility, View.VISIBLE)