Skip to content Skip to sidebar Skip to footer

Add Controls To Custom Dialog Programmatically

I want to show a dialog with ~50 custom controls (switch buttons) on it. So, the best way to do that is to add them programmatically in a loop. I've tried to make a dilog with a la

Solution 1:

The problems in your code were pretty obvious:

  • In your layout file you use ViewGroup which is an abstract class(the root of all layouts in Android) and which can't be instantiated so it will most likely be the reason for that inflate exception you talk about. Use one of the subclasses of ViewGroup, like LinearLayout, RelativeLayout etc, which one fits you better.

  • Even after doing the modification I wrote above your code will still bot work. First the ViewGroup class doesn't have an add method, you're probably referring to one of the addView methods. Second the dlgView will be null because at that moment the Dialog isn't displayed so there is no View to find. You can do it by posting a Runnable on one of your views to delay setting the views until the Dialog is shown:

    final Dialog res = builder.create();
    oneOfYourViews.post(new Runnable() {
    
        @Override
        public void run() {
            ViewGroup dlgView = (ViewGroup) res.findViewById(R.id.dlg_view);
            MyControl myControl = new MyControl(context);
            dlgView.addView(myControl);             
        }
    });
    

Code addition:

View contentView = inflater.inflate(R.layout.geomap_menu, null)
ViewGroup dlgView = (ViewGroup) contentView.findViewById(R.id.dlg_view);
MyControl myControl = new MyControl(this);
dlgView.addView(myControl); // or add the other views in the loop as many as you want
builder.setView(contentView);
// rest of your code

Post a Comment for "Add Controls To Custom Dialog Programmatically"