Custom listview for AlertDialog

我的未来我决定 提交于 2019-12-21 17:20:03

问题


I'm trying to have my AlertDialog with a custom list view but can't seem to get it to show or run without error.

   private void buildDialog(){

        int selectedItem = -1; //somehow get your previously selected choice
        LayoutInflater inflater = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
        View customView = inflater.inflate(R.layout.listview, null, false);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(customView);
        builder.setTitle("Select Weapon").setCancelable(true);
        builder.setSingleChoiceItems(inventory, selectedItem, "Desc", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which)
            { 
                ListView lv = ((AlertDialog) dialog).getListView();
                itemId = lv.getAdapter().getItemId(which);
                new changeEQ().execute();
            }
        });



        dialog = builder.create();
    }

This is my AlertDialog but can't figure out what to add to get my custom layouts, listview & listrow to be used. I've looked around at guides online but nothing they show seems to work for me. IE I must be doing something wrong.

EDIT: changed code to include answer but has no change on what is showed on screen. No errors yet no change in look.


回答1:


If you have a custom layout that you want to pass to your AlertDialog try:

LayoutInflater inflater = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
View customView = inflater.inflate(R.layout.custom_dialog, null, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(customView);

If you want to define listeners try:

ListView list = (ListView) customView.findViewById(R.id.listView1);
list.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // Do as you please
    }
});


来源:https://stackoverflow.com/questions/10367934/custom-listview-for-alertdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!