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.

回答1:

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.



回答2:

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();
    }


回答3:

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));


回答4:

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.



回答5:

if(cdata.getCount()>0)
{
    CursorAdapter adapter = new MyCursorAdapter( getApplicationContext(), R.layout.listview, cdata, fields, names);
    listview.setAdapter(adapter);
}
else
{
    //create dialog here
}