MegaWidget MegaWidget - 28 days ago 3x
Android Question

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) {
this.context = context;

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

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

private void initViews() {
// Init typeSpinner
typeSpinner = (Spinner) findViewById(;

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

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?


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(...)