简体   繁体   中英

Sum of EditTexts values

Here I have two EditText widgets (numbers only), and I want to find sum of values from these widgets and put it to TextView.

Here's my MainActivity.kt :


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    var resultText = findViewById<android.widget.TextView>(R.id.textView)
    public fun plus(){
        val editText1: Int = findViewById<android.widget.EditText>(R.id.editTextNumber).text.toString().toInt()
        val editText2: Int = findViewById<android.widget.EditText>(R.id.editTextNumber2).text.toString().toInt()
        resultText.setText(editText1 + editText2)
    }
}```

TextView has a method setText() which takes resource Id as int, if you do sum inside setText(), it means you are passing int and there might be a resource not found exception. You need to pass sum as string to setText() .

change this line

resultText.setText(editText1 + editText2)

to this

resultText.setText("" + (editText1 + editText2))

first line is using setText(int stringResourceId) , but you are passing just sum, its not resource id. So convert this sum to String , then set to resultText using setText(String text)

add some Button to your layout ( R.layout.activity_main ), attach OnClickListener to it (eg inside onCreate ) and call plus() method inside onClick method of listener

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM