简体   繁体   English

如何使 EditText 不为空?

[英]How to make EditText not empty?

I have an editText and button.我有一个 editText 和按钮。 EditText is for users' names. EditText 用于用户名。 I have a problem, my code below.我有问题,我的代码如下。

 String fullname = editText.getText().toString();
    if (TextUtils.isEmpty(fullname)){
        Toast.makeText(this, "Name should not be empty", Toast.LENGTH_SHORT).show();

My problem is when the user clicks on the button without putting anything, toast message show;我的问题是当用户点击按钮而不放置任何东西时,吐司消息显示; which is fine but when the user put space it stores fullname value empty.这很好,但是当用户放置空间时,它会将全名值存储为空。 I don't want empty value.我不想要空值。

You should trim the input: fullname.trim().isEmpty() to get rid of leading and trailing whitespace.您应该修剪输入: fullname.trim().isEmpty()以去除前导和尾随空格。 So if you have an input with just whitespace, it will consider it empty.所以如果你有一个只有空格的输入,它会认为它是空的。

I would disable the button when the text is invalid.当文本无效时,我会禁用该按钮。 It's better to validate earlier rather than allow an action prematurely.最好尽早验证而不是过早地允许操作。 It's also possible, using the TextWatcher to modify the user input to remove invalid spaces etc.也可以使用TextWatcher修改用户输入以删除无效空格等。

        <EditText
            android:id="@+id/editText"
            android:layout_margin="16dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white"/>

        <Button
            android:id="@+id/button"
            android:layout_margin="16dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@android:string/ok"/>

In activity or fragment:在活动或片段中:

    editText.addTextChangedListener(
            object : TextWatcher {
                override fun afterTextChanged(s: Editable) {
                    button.isEnabled = s.trim().isNotEmpty()
                }

                override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

                override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}

            }
    )

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

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