Android - Display Alert Dialog for empty ListView

2019-05-23 18:16发布

How to show the alert dialog for the empty list view when there are no listview items. Please find the below image having three text fields. I have to implement the empty list view when there are no records/unmatched records in the list.

The list view is implemented as below:

ListView empListView; 
empListView = (ListView)findViewById(R.id.list1 );

I have to show the alert dialog box for the empListView. Please help me with the samplecode/links.

5条回答
你好瞎i
2楼-- · 2019-05-23 18:25
if(cdata.getCount()>0)
{
    CursorAdapter adapter = new MyCursorAdapter( getApplicationContext(), R.layout.listview, cdata, fields, names);
    listview.setAdapter(adapter);
}
else
{
    //create dialog here
}
查看更多
放荡不羁爱自由
3楼-- · 2019-05-23 18:30

I think you are paasing arraylist or some other data in setadapter method And if you are using arraylist then you have to check that size of arraylist before calling the setadapter method.

if(a.size()>0)
    {
    lv = (ListView) findViewById(R.id.frendlist);
    lv.setAdapter(new ListAdapter(this, R.id.frendlist, a));
    }
    else
    {
        builder.setMessage(" You Have no friends") 
        .setCancelable(false)   
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() 
        {      
            public void onClick(DialogInterface dialog, int id)
            {

            }   
            }) ; 

        AlertDialog alert = builder.create();
        alert.show();
    }
查看更多
Bombasti
4楼-- · 2019-05-23 18:37

It all depends on how you implement the setAdapter method etc. But here is an example:

if(cdata.getCount()==0) {
  //empty, show alertDialog
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setMessage("Search is empty")
   .setCancelable(true)
   .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
       }
   });
  AlertDialog alert = builder.create();
} 
else {
  //Not empty, set the adapter or do what you want. 
  empListview.setAdapter(new MyCursorAdapter( getApplicationContext(), R.layout.listview, cdata, fields, names));
}

The code above havent been tested. But should work with minor adjustments, I might have forgotten something.

查看更多
Deceive 欺骗
5楼-- · 2019-05-23 18:39

I think you are paasing arraylist or some other data in setadapter method And if you are using arraylist then you have to check that size of arraylist before calling the setadapter method.

查看更多
再贱就再见
6楼-- · 2019-05-23 18:44

As per my opinion, No need to check the size of arraylist or adapter item count.

Instead of displaying alert dialog, you can just display message "Sorry no records found" message on the listview. for the same you have to set the empty view by using setEmptyView() method of ListView.

For example:

listViewFriends.setEmptyView(findViewById(R.id.empty));
查看更多
登录 后发表回答