2016-09-22 27 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

相關問題