在我的自定义ListView项上,为什么(string.length()<= 0)始终为true,而(string =="")始终为false?

der*_*rik 1 java android

我已经创建了一个自定义ListView适配器/项目.该项包含CheckedTextView和TextView.

在适配器的getView()方法中,创建自定义项并在返回之前调用其setTask(Task)方法.

setTask(Task)方法从作为参数传入的Task对象获取2个字符串和一个布尔值.(我确实认识到它的地址实际上是传递的.)

其中一个字符串被分配给自定义项的TextView的文本属性,如果该字符串包含文本.否则,TextView的visible属性设置为"已消失".

为了做出这个决定,我检查字符串的长度是否小于或等于0 ......它会产生意外的行为 - 它总是评估为真.

如果我更改它以检查String是否等于"",它总是返回false.

这让我相信我正在检查的String是null.那为什么会这样?

protected void onFinishInflate() {
    super.onFinishInflate();
    checkbox = (CheckedTextView)findViewById(android.R.id.text1);   
    description = (TextView)findViewById(R.id.description);
}

public void setTask(Task t) {
    task = t;
    checkbox.setText(t.getName());
    checkbox.setChecked(t.isComplete());
    if (t.getDescription().length() <= 0)
        description.setVisibility(GONE);
    else
        description.setText(t.getDescription());
}
Run Code Online (Sandbox Code Playgroud)

这是适配器中的getView()方法:

public View getView(int position, View convertView, ViewGroup parent) {

    TaskListItem tli;
    if (convertView == null)
        tli = (TaskListItem)View.inflate(context, R.layout.task_list_item, null);
    else
        tli = (TaskListItem)convertView;

    tli.setTask(currentTasks.get(position));
    return tli; 
}
Run Code Online (Sandbox Code Playgroud)

Spi*_*idy 6

myString == ""
Run Code Online (Sandbox Code Playgroud)

检查字符串对象的引用而不是内容.你应该使用:

"".equals(myString)
Run Code Online (Sandbox Code Playgroud)

它检查字符串的内容,而不是参考.你可以使用:

myString.equals("")
Run Code Online (Sandbox Code Playgroud)

但如果myString为null,则有可能出现NullPointerException.