2012-11-02 26 views
0

我有一個自定義組件實際上包裝另一個組件。它的佈局是:從膨脹創建錯誤的佈局層次

<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" android:layout_height="match_parent" 
android:background="@drawable/text_view_background" android:textCursorDrawable="@null" 
android:textColor="@android:color/black" android:inputType="textNoSuggestions" 
android:paddingLeft="7dp"/> 

在組件的代碼我想它充氣:

inflate(context,R.layout.results_auto_complete,this); 
resultsAutoComplete=(AutoCompleteTextView)getChildAt(0); 

但我發現了一個ClassCastException,它說的第一個孩子是一個RelativeLayout!我追蹤了這個相對佈局的所有子元素,它實際上是配置活動包含我的自定義元素的構件的佈局!當我用簡單的測試活動測試組件時,一切都奏效了!

那麼爲什麼會發生這種情況,我該怎麼辦? 謝謝。

回答

0

看來問題是,我有2個佈局與來自不同項目中的相同標識符(一個項目鏈接到其他的),所以當我試圖從一個項目中擴充佈局,我在另一個項目中獲得具有相同標識符的佈局。無論如何,感謝您的幫助。

0

如果您的AutoCompleteTextViewresults_auto_complete.xml的獨立xml文件(您的代碼是根xml標籤)。這是通貨膨脹的結果,不需要使用getChildAt(i)。

如果<AutoCompleteTextView>是XML文件中的子元素,則應使用它爲其分配Id:android:id="@+id/your_view_id"。然後膨脹後,可以使用:

this.findViewById(R.your_view_id); 

其中這是它加載組件視圖當前活動。

更新,試試這個:

LayoutInflater mInflater = (LayoutInflater)etContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
resultsAutoComplete=(AutoCompleteTextView)mInflater.inflate(R.layout.your_view_id, this, true); 
+0

這是根本元素,當我使用測試活動時,它確實是通貨膨脹的結果,我不需要調用getChildAt。我只是因爲組件處於小部件的配置活動時得到的奇怪結果而添加它。 – user940016

+0

請嘗試更新的代碼! – CuongKe

+0

對不起,它沒有工作。 'inflate'函數返回我的組件(這是預期的,因爲根據文檔,它返回提供給函數的根視圖組,如果提供的話),並且它的第一個孩子再次是應用部件的根... – user940016