-2

I would like the equivalent code for the line below in Kotlin:

TextView tv = view.findViewbyId(R.id.textView);

Any help?

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Fazal
  • 122
  • 2
  • 9

8 Answers8

3

very simply, just do following action

val valueName = view!!.findViewById<ObjectName>(R.id.ObjectId)

also with this mark !! kotlin will be checked null state

finally see following example

val btn = view!!.findViewById<Button>(R.id.btn)
Saeed
  • 412
  • 5
  • 16
  • I think, that's a mistake. If view will be null (it often happens), an application will crash. So, instead of `view!!` it should be written as `view?`. – CoolMind Sep 11 '18 at 06:58
2

Why don't you simply use Kotlin Android Binding? Which is an Extension from Kotlin helps to bind the view without any "bindView" or findViewById code to interfere business logic.

Once you have dig into it, you would definitely find it great and less code written afterwards.

Worth to have a look. https://kotlinlang.org/docs/tutorials/android-plugin.html


But you can still use the original one with kotlin

val lblLabel = findViewById(R.id.text) as TextView
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
dwqdq13213
  • 317
  • 1
  • 10
1

Initialization of view in fragment :

val manageAddress=view.findViewById<TextView>(R.id.textView)

that's it

0
 val tv: TextView = findViewById(R.id.textView) as TextView

if you want to declare textview globally, use lateinit var tv: TextView

SARATH V
  • 500
  • 1
  • 7
  • 33
0

like this you can do in kotlin

val lv = findViewById(R.id.textView) as TextView
Sunil P
  • 3,698
  • 3
  • 13
  • 20
0

Kotlin Initialization:

val tv = findViewbyId(R.id.textView) as TextView

Refer here

Gowtham Subramaniam
  • 3,358
  • 2
  • 19
  • 31
0

You can use:

val myLabel = findViewById(R.id.text) as TextView

However you can use the Kotlin Android Extensions plugin.

Just add to your build.gradle

apply plugin: 'kotlin-android-extensions'

Then you can avoid the use of the findViewById method just using for example:

textView.text = "My text"

You can access the view without finding it or using third party libraries just using the id assigned in the xml file.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
0

If you use Kotlin Android Extensions (apply plugin: 'kotlin-android-extensions', see https://antonioleiva.com/kotlin-android-extensions/), you can write textView and IDE will offer several variants of that view in different layouts. After you choose a right one, you can write something like:

textView.text = "This is a text"

In imports you will see something like import kotlinx.android.synthetic.main.fragment_dialog.*

CoolMind
  • 26,736
  • 15
  • 188
  • 224