检查textview是否为空?

np8igboo  于 2021-07-03  发布在  Java
关注(0)|答案(4)|浏览(228)

我正在一张照片上显示一个日期 TextView . 有约会的时候一切都很好。但是如果没有选择日期或者 TextView 如果是空的(但是有一个提示“dd-mm-yyyy”),那么应用程序就会崩溃。我正在检查是否有空的 TextView 具体如下: if(textview.setText().toString().isEmpty()) {//show error} 有人能帮我做错事吗?
初始化 TextView 以及 TextInputlayout :

tv_Current_Date = (TextView) findViewById(R.id.tv_Current_Date);
til_Current_Date = (TextInputLayout) findViewById(R.id.til_Current_Date);

以下是导致崩溃的代码:

if (tv_Current_Date.getText().toString().isEmpty()) {
    til_Current_Date.setError("Please choose a date");
}

设置日期的方法:

public void setCurrentDateOnView() {
    String dateFormat = "dd-MM-yyyy";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
    tv_Current_Date = (TextView) findViewById(R.id.tv_Current_Date);
    tv_Current_Date.setText(simpleDateFormat.format(calendar_now.getTime()));
    String short_weekday = new DateFormatSymbols().getShortWeekdays()[day_of_current_week];
    tv_Current_weekday.setText(short_weekday);
}
a5g8bdjr

a5g8bdjr1#

试试这个

if(tv_Current_Date.getText().toString().equals("") && tv_Current_Date.getText().length() <= 0){
   tv_Current_Date.setError("your message");
}
tcomlyy6

tcomlyy62#

除了if条件外,还需要else条件来运行代码。

if (tv_Current_Date.getText().toString().isEmpty()) {
                til_Current_Date.setError("Please choose a date");
            } else{ put the code here}
gblwokeq

gblwokeq3#

除了tejas和joao86所说的之外,您应该检查并验证输入实际上是一个日期。
查看他们讨论验证的以下链接:
android中的日期验证
如何在android的editext中验证dd/mm/yyyy格式的日期?
java:检查当前字符串的日期格式是否符合要求的格式

ct3nt3jp

ct3nt3jp4#

试试这个

if (tv_Current_Date.getText().toString().equals("")) {
      til_Current_Date.setError("Please choose a date");
}

相关问题