Android 编辑文本值之和
这里我有两个EditText小部件(仅限数字),我想从这些小部件中找到值的总和并将其放入TextView 这是我的主要活动。kt:Android 编辑文本值之和,android,android-studio,kotlin,Android,Android Studio,Kotlin,这里我有两个EditText小部件(仅限数字),我想从这些小部件中找到值的总和并将其放入TextView 这是我的主要活动。kt: import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.EditText import android.widget.TextView class MainActivity : AppCompatActivity() {
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)
}
}```
导入androidx.appcompat.app.appcompat活动
导入android.os.Bundle
导入android.widget.EditText
导入android.widget.TextView
类MainActivity:AppCompatActivity(){
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
var resultText=findViewById(R.id.textView)
公共娱乐+(){
val editText1:Int=findViewById(R.id.editTextNumber).text.toString().toInt()
val editText2:Int=findViewById(R.id.editTextNumber2).text.toString().toInt()
resultText.setText(editText1+editText2)
}
}```
TextView有一个方法setText(),该方法将资源Id作为int,如果您在setText()内进行求和,则表示您正在传递int,并且可能存在资源未找到异常您需要将sum作为字符串传递给setText()更改此行
resultText.setText(editText1 + editText2)
对此
resultText.setText("" + (editText1 + editText2))
第一行使用的是setText(int-stringResourceId)
,但您只传递了sum,而不是资源id。因此,请将此sum转换为String
,然后使用setText(String text)
设置为resultText
将一些
按钮
添加到布局(R.layout.activity\u main
),将OnClickListener
附加到它(例如,在onCreate
内部),并调用plus()
监听器的方法内部onClick
方法,当EditText文本更改时,您需要回调。为每个EditText添加一个TextWatcher
,以完成此操作。或者只需添加一个按钮,在单击时调用plus()
。不起作用。。。在末尾添加了.toString
。现在看起来是这样的:resultText.setText((editText1+editText2.toString())
.toString应该可以工作。可能还有其他问题。你能补充一下你的问题吗