当 ListView 为空时制作 Toast

make Toast when ListView is empty

我想在我的列表视图为空时显示一个 Toast,我试过了但是它不起作用,我不明白为什么:

if (listView == null) {
        Toast.makeText(this, "No slots selected",
                Toast.LENGTH_LONG).show();
    }

我知道 Toast 是如何工作的,但我的问题是检测列表视图何时为空。

有人能帮我吗?

您需要检查附加到 ListView 的列表的大小。

假设列表是附加到 ListView 的 ArrayList

if(list.size()==0)
{
//Perform Action
}

你也可以用这个

if(list!=null && !list.isEmpty())
{
     //Show Listview
} else {
     //Show Toast (List Empty)
}

Instead of listview you should keep track of count for adapter attached to listView.

试试

if(listViewAdapter.getItemCount.size()==0){
    // Toast Message
}else{
    // Populate your data
}

Instead of listview you should keep track of count for list attached to listView.

if(list.size()==0){
        // Toast Message
    }else{
        // Populate your data
    }

您需要检查附加到您的 ListView 的列表(通过适配器)。 创建列表时,您无法通过 == null 检查,因为变量已经创建。

改为检查列表大小,如下所示:

adapter.getCount() == 0
if(listView.getCount() == 0 )
    Toast.makeText(dd.this, "The list is empty", Toast.LENGTH_SHORT).show();