Home > OS >  View in accessible in kotlin classs, Android Studio
View in accessible in kotlin classs, Android Studio

Time:08-31

    <EditText
    android:id="@ id/editText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="104dp"
    android:ems="10"
    android:inputType="textPersonName"
    android:hint = 'your name'
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@ id/textView" />

This is my main xml file and I'm trying to get the input using EditText View. But in kotlin file this view is not accessible, it suggests to create a new variable

    val name  = editText.text.toString()
    Toast.makeText(this, "name is $name", Toast.LENGTH_SHORT).show()

editText is not recognized

CodePudding user response:

If you want to access edittext then first you do findViewById() like this

val edtName = findViewById<EditText>(R.id.editText)

Now you can access your editext like this

val name  = edtName.text.toString()
Toast.makeText(this, "name is $name", Toast.LENGTH_SHORT).show()

if you use View Binding then you don't need to use findViewById() to bind your view in your activity file

Please read more about View Binding

  • Related