Search code examples
androidcustom-componentlayout-inflater

Passing "this" as root to LayoutInflater.inflate() in a custom component


I am writing the code for a custom component that extends LinearLayout. It will include a Spinner at the top, and some number of settings below, depending on what the Spinner is set to. i.e., when the user selects "Apple" on the spinner, a "color" option appears, and when they select "Banana" a "length" option appears.

Since a spinner option might have many settings associated with it, I define each group of settings in a layout XML with "merge" as the root tag. Then I call initViews() in each constructor to inflate the views so I can add/remove them later.

Here is the code for the class:

    public class SchedulePickerView extends LinearLayout {
        protected Context context;

        protected Spinner typeSpinner;
        protected ViewGroup defaultSetters;  // ViewGroup to show when no schedule is selected in the spinner
        protected ViewGroup simpleSetters;   // ViewGroup to show when SimpleSchedule is selected in the spinner

        public SchedulePickerView(Context context) {
            super(context);
            this.context = context;
            initViews();
        }

        public SchedulePickerView(Context context, AttributeSet attr) {
            super(context, attr);
            this.context = context;
            initViews();
        }

        public SchedulePickerView(Context context, AttributeSet attr, int defstyle) {
            super(context, attr, defstyle);
            this.context = context;
            initViews();
        }

        private void initViews() {
            // Init typeSpinner
            typeSpinner = (Spinner) findViewById(R.id.schedulepickerSpinner);

            // Init setters (ViewGroups that show settings for the various types of schedules
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // ERROR IS ON THIS LINE:
            defaultSetters = inflater.inflate(R.layout.container_schedulesetter_default, this);
        }
   }

I get this error on the marked line: "Incompatible types: Required = ViewGroup, Found = View". But LinearLayout extends ViewGroup, as per this documentation. I have even tried casting "this" to a ViewGroup, but strangely the IDE greyed-out the cast (since, obviously, every LinearLayout is already a ViewGroup). So why is there an issue?


Solution

  • inflate() returns a View and you're trying to assign it to a more specific ViewGroup variable. It's not the this as parent view that is problematic - you need a cast on the return value:

    defaultSetters = (ViewGroup)inflater.inflate(...)