Home > OS >  why doesn't setText of TextView work in android studio in kotlin?
why doesn't setText of TextView work in android studio in kotlin?

Time:01-11

i discovered in android studio setText of TextView doesn't work. see next code. I expect if in nextCode append button is clicked, in textView text is changed to editText.text.toString(). but doesn't be changed. why so? Activity.kt :

package com.example.myapplication

import android.content.Context
import android.content.Context.LAYOUT_INFLATER_SERVICE
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val editText = findViewById(R.id.editText) as EditText
        val textView = findViewById(R.id.textView) as TextView
        val button = findViewById(R.id.button) as Button
        button.setOnClickListener(View.OnClickListener(){
            @Override
            fun onClick(view : View){
                textView.setText(editText.text.toString())
            }
        })
    }
}

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:id="@ id/root_layout">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@ id/editText"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="append"
        android:id="@ id/button"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ id/textView"
        android:text="4"/>

</LinearLayout>

CodePudding user response:

You are not setting up the click listener properly. Either specify

button.setOnClickListener(object : View.OnClickListener {
    override fun onClick(view: View) {
        textView.setText(editText.text.toString())
    }
})

or the lambda construction:

button.setOnClickListener {
    textView.setText(editText.text.toString())
}
  •  Tags:  
  • Related