Why can't I call SetText on it which is

50 views Asked by At

I wanted to display text in EditText when I clicked on this. But using it does not allow this.

`class MainActivity : AppCompatActivity() {

private val MY_LOG = "myLog"
lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
        .also {
            setContentView(it.root)
        }

    binding.etTest.setOnClickListener {
        binding.etTest.setText("$it")
        it.setText("String")

    }
}

}`

enter image description here

Why if "it" is EditText not working setText()?

2

There are 2 answers

0
Rujul Gandhi On

Basically OnClickListener is interface which has onClick method which will give you View class and View class doesn't have any method for setText. Due to that you are not able to call setText method.

OnClickListener implementation

1
Abdelrahman Mahmoud Nasr On

The reason why it.setText("String") doesn't work is because the it variable in the binding.etTest.setOnClickListener lambda refers to the View that was clicked, not specifically to the EditText itself. In this case the View that was clicked is the RelativeLayout , ConstraintLayout , etc... that contains the EditText.

So don't use it

You should use the actual view like in this case is the editText

You have to just call setText on the edittext

If you want to set the text when the edittext is clicked

    binding.etTest.setOnClickListener {
        binding.etTest.setText("Your text")
    }

and If you want to get the text from the edittext

    val text = binding.etTest.text

and voila