如何在警告对话框中膨胀包含listview的布局?

arn*_*rnp 12 android listview android-alertdialog custom-adapter

我在布局中使用带有自定义适配器的listview.现在我试图将包含列表的布局带到我的alertdialog.我尝试将不包含列表的简单布局带到此代码的警告对话框,并且它运行良好.但我无法将包含布局的列表带入alertdialog.

           AlertDialog.Builder dialog = new AlertDialog.Builder( this );
           dialog.setView( getLayoutInflater().inflate( R.layout.smill, null ) );
           dialog.setIcon(R.drawable.androidsmile);
           dialog.setInverseBackgroundForced(true);


           dialog.setTitle( "Select smiley");
           dialog.setPositiveButton( "Cancel", null );
           dialog.show();  
Run Code Online (Sandbox Code Playgroud)

dym*_*meh 17

您所做的就是将视图扩展到警报对话框中.您没有在该列表视图上设置适配器,所以当然它似乎不起作用(因为它是空的).

你需要做一些事情:

View view = getLayoutInflater().inflate( R.layout.smill, null);
ListView listView = (ListView) view.findViewById(R.id.listView);
YourCustomAdapter adapter = new YourCustomAdapter(parameters...);
listView.setAdapter(adapter);

AlertDialog.Builder dialog = new AlertDialog.Builder( this );
dialog.setView(view);
...
...
...
dialog.show();  
Run Code Online (Sandbox Code Playgroud)

  • 避免传递null作为layoutInflater的根视图.如果在适配器内部完成此操作,则可以传递rootview或convertview或托管此警报对话框的任何视图 (2认同)