繁体   English   中英

我想知道 kotlin、android 工作室中的“如何检查按钮单击时编辑文本是否为空”,因为我的代码不起作用

[英]I want to know "how to check that edittext is empty on button click" in kotlin, android studio because my code is not working

这是我的代码,在 XML 中没有问题,所有视图的 id 都是正确的

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val button: Button = findViewById(R.id.button)
        val stringInTextField:EditText = findViewById(R.id.bill)
        button.setOnClickListener(View.OnClickListener{
        val userInput = stringInTextField.text.toString()
        if (userInput.isEmpty) {
            Toast.makeText(this, "Please Enter the Bill", Toast.LENGTH_SHORT).show()
        }
    })
}

您的代码中有错误,因为String class 没有属性isEmpty而是方法isEmpty() 因此,修复该错误以使其正常工作:

if (userInput.isEmpty()) { // Here is the fix
    Toast.makeText(this, "Please Enter the Bill", Toast.LENGTH_SHORT).show()
}

if (.userInput.equals(""))你可以试试这个代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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