Shailendra Madda
Shailendra Madda

Reputation: 21551

Android kotlin butterknife view visibility

I was trying to set the visibility of a view in android using ButterKnife with Kotlin

I got the id in butterknife like:

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

The visibility can be set in Java like: (As we know)

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

I tried: progress.visibility to .... ?

How will it be in kotlin with ButterKnife?

Upvotes: 0

Views: 621

Answers (2)

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

Try with

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

Note

You should use 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.

Example

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 
        }
    }

Upvotes: 1

zsmb13
zsmb13

Reputation: 89558

You can use the same setters in Kotlin:

progress.setVisibility(View.VISIBLE)

You can also use a property access syntax instead, which does the exact same thing:

progress.visibility = View.VISIBLE

As for the last part of your question, if you were trying to write this:

progress.visibility to View.VISIBLE

Then all that does is create a Pair which is never used and just thrown away - it's equivalent to this:

Pair(progress.visibility, View.VISIBLE)

Upvotes: 2

Related Questions