2016-09-22 73 views
0

我正在编写扩展LinearLayout的自定义组件的代码。它将在顶部包含一个微调器,并根据微调器的设置,在下面进行一些设置。即,当用户在微调器上选择“苹果”时,出现“颜色”选项,并且当他们选择“香蕉”时出现“长度”选项。将“this”作为根传递给自定义组件中的LayoutInflater.inflate()

由于微调器选项可能具有许多与其关联的设置,因此我使用“合并”作为根标记在布局XML中定义每组设置。然后我在每个构造函数中调用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); 
     } 
    } 

我上标线这个错误:“不兼容类型:所需= ViewGroup中,找到=查看”。但LinearLayout根据this文档扩展了ViewGroup。我甚至尝试将“this”投射到一个ViewGroup,但奇怪的是IDE使投射变灰(因为显然,每个LinearLayout已经是一个ViewGroup)。那么为什么会有问题呢?

+0

尝试使用classname.this – Kushan

+0

可以告诉你更多的代码? – ligi

+0

请附上您的完整控制代码。 –

回答

2

inflate()返回一个View,并且您试图将其分配给更具体的ViewGroup变量。这不是this因为这是有问题的父视图 - 你需要在返回值的转换:

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

当然!我以为IDE是说这个方法调用本身是一个错误,但它是变量赋值。谢谢! – MegaWidget

相关问题