我已经创建了一个自定义的 ListView 适配器/项。该项目包含一个 CheckedTextView 和一个 TextView。
在适配器的 getView() 方法中,创建自定义项并在它返回之前立即调用其 setTask(Task) 方法。
setTask(Task) 方法从作为参数传入的 Task 对象中获取 2 个字符串和一个 boolean 值。 (我确实认识到它的地址实际上是通过的地址。)
其中一个字符串被分配给自定义项的 TextView 的文本属性,如果该字符串包含文本。否则,TextView 的可见属性设置为“消失”。
为了做出该决定,我检查字符串的长度是否小于或等于 0...它会产生意想不到的行为 - 它总是评估为真。
如果我更改它以检查字符串是否等于“”,它总是返回 false。
这让我相信我正在检查的字符串是空的。为什么会这样?
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());
}
这是适配器中的 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;
}
最佳答案
myString == ""
检查字符串对象的引用而不是内容。你应该使用:
"".equals(myString)
检查字符串的内容,而不是引用。你可以使用:
myString.equals("")
但如果 myString 为空,则有可能出现 NullPointerException。
关于java - 在我的自定义 ListView 项上,为什么 (string.length() <= 0) 始终为真,而 (string == "") 始终为假?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6447027/