0

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?

Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138

2 Answers2

2

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)
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • As I said I tried `progress.setVisibility(View.VISIBLE)` but not worked, is it mandatory to use `kotlinx.android.synthetic`? – Shailendra Madda Apr 15 '18 at 17:21
  • Thanx, I don't know why it's not worked before, I just restarted my studio `progress.visibility = View.VISIBLE` is made it work. – Shailendra Madda Apr 15 '18 at 17:25
  • 1
    It's definitely not mandatory to use the Kotlin Android Extensions plugin by any means. It's just one of the available options (to see others, see [this question](https://stackoverflow.com/q/44285703/4465208)). If you're comfortable using ButterKnife, you can absolutely keep using it with Kotlin. – zsmb13 Apr 15 '18 at 17:35
1

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 
        }
    }
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198