Android 通行证;这";作为自定义组件中LayoutInflater.inflate()的根

Android 通行证;这";作为自定义组件中LayoutInflater.inflate()的根,android,custom-component,layout-inflater,Android,Custom Component,Layout Inflater,我正在为扩展LinearLayout的自定义组件编写代码。它将包括顶部的微调器和下面的一些设置,具体取决于微调器的设置。i、 例如,当用户在微调器上选择“苹果”时,将显示“颜色”选项,当用户选择“香蕉”时,将显示“长度”选项 由于微调器选项可能有许多与之关联的设置,因此我在布局XML中定义每组设置,并将“merge”作为根标记。然后,我在每个构造函数中调用initViews()来膨胀视图,以便以后添加/删除它们 下面是该类的代码: public class SchedulePickerV

我正在为扩展LinearLayout的自定义组件编写代码。它将包括顶部的微调器和下面的一些设置,具体取决于微调器的设置。i、 例如,当用户在微调器上选择“苹果”时,将显示“颜色”选项,当用户选择“香蕉”时,将显示“长度”选项

由于微调器选项可能有许多与之关联的设置,因此我在布局XML中定义每组设置,并将“merge”作为根标记。然后,我在每个构造函数中调用initViews()来膨胀视图,以便以后添加/删除它们

下面是该类的代码:

    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);
        }
   }
我在标记的行中得到了这个错误:“不兼容的类型:Required=ViewGroup,Found=View”。但根据文档,LinearLayout扩展了ViewGroup。我甚至尝试将“this”转换为一个视图组,但奇怪的是IDE将转换为灰色(因为很明显,每个LinearLayout都已经是一个视图组)。那么为什么会出现问题呢?

inflate()
返回一个
视图
,您试图将其分配给一个更具体的
视图组
变量。问题不在于
这个
作为父视图-您需要对返回值进行强制转换:

defaultSetters = (ViewGroup)inflater.inflate(...)
inflate()
返回一个
视图
,您试图将其分配给一个更具体的
视图组
变量。问题不在于
这个
作为父视图-您需要对返回值进行强制转换:

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

尝试使用类名。这可以显示更多的代码吗?请附上完整的控制代码。@ligi已经编辑了文章,包括周围的代码和我得到的错误。提前感谢。请尝试使用类名。这可以显示更多代码吗?请附上完整的控制代码。@ligi已编辑文章,包括周围的代码和我收到的错误。提前谢谢,当然!我以为IDE说方法调用本身是一个错误,但这是变量赋值。非常感谢。当然我以为IDE说方法调用本身是一个错误,但这是变量赋值。非常感谢。