【发布时间】:2016-08-20 13:28:38
【问题描述】:
我正在尝试检查用户是否在按钮单击事件的 EditText 中输入了他/她的手机号码,但是当控制“editRegMobile”时我无法检查 EditText 是否为空”。当我单击按钮时,它不会在 Toast 中显示消息。我还想检查手机号码的格式,即“+91 999999999”国家代码。我可以检查其他 EditText,但不能检查 Mobile EditText。
xml代码:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="@+id/editRegMobile"
android:layout_gravity="center_horizontal"
android:background="@drawable/sign_in_up_textbox"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="35dp"
android:textSize="16sp"
android:letterSpacing="0.08"
android:singleLine="true" />
Java 代码:
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (editRegName != null && TextUtils.isEmpty(editRegName.getText().toString().trim())) {
editRegName.setError("Required!");
editRegName.requestFocus();
} else if (editRegEmail != null && TextUtils.isEmpty(editRegEmail.getText().toString())) {
editRegEmail.setError("Required!");
editRegEmail.requestFocus();
} else if (!(editRegEmail != null && TextUtils.isEmpty(editRegEmail.getText().toString()))) {
if (!Patterns.EMAIL_ADDRESS.matcher(editRegEmail.getText().toString()).matches()) {
editRegEmail.setError("Invalid Format!");
editRegEmail.requestFocus();
}
} else if ((editRegMobile != null) && TextUtils.isEmpty(editRegMobile.getText().toString())) {
Toast.makeText(getApplicationContext(), "Please enter mobile number!", Toast.LENGTH_SHORT).show();
} else if (!(editRegMobile != null && TextUtils.isEmpty(editRegMobile.getText().toString()))) {
if (!Patterns.PHONE.matcher(editRegMobile.getText().toString()).matches()) {
Toast.makeText(getApplicationContext(), "Please enter valid mobile number!", Toast.LENGTH_SHORT).show();
}
}
}
});
【问题讨论】:
-
您不需要执行 editRegMobile.getText().toString() 只需执行 editRegMobile.getText()
-
顺便说一句,
TextUtils.isEmpty已经检查了 null 或空字符串。 (理想情况下,您的视图对象不应为空)而且您只需要一个else语句。无需否定整个if条件
标签: android