Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom listview for AlertDialog

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.

like image 412
maebe Avatar asked Apr 28 '12 22:04

maebe


People also ask

How to show List in AlertDialog Android?

Navigate to the app > res > layout and create a new layout file. Add a ListView as shown below. This layout would be displayed inside the AlertDialog.

What is AlertDialog message?

Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can be used to interrupt and ask the user about his/her choice to continue or discontinue. Android AlertDialog is composed of three regions: title, content area and action buttons.

How many types of dialogs are there in Android?

There are three kinds of lists available with the AlertDialog APIs: A traditional single-choice list. A persistent single-choice list (radio buttons) A persistent multiple-choice list (checkboxes)


1 Answers

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
    }
});
like image 55
Sam Avatar answered Sep 28 '22 16:09

Sam