2011-12-31 85 views
1

我有一個ViewSwitcher和希望的意見添加到它:View.addView()拋出IllegalStateException異常(ViewSwitcher)`

// initialize views 
    final ViewSwitcher switcher = new ViewSwitcher(this); 
    layMenu = (LinearLayout)findViewById(R.id.menu_main_view); 
    final LevelPicker levelPicker = new LevelPicker(getApplicationContext()); 

    (//)switcher.addView(layMenu); 
    (//)switcher.addView(findViewById(R.layout.menu_switcher)); 

一個是一個自定義視圖,從XML另外一個。我評論他們中的一個,但他們似乎都扔IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

我想這樣做就像把意見在「容器」第一個(另一個佈局)幾件事情,或者試圖removeView((視圖)的getParent),就像我相信在logcat的嘗試說..

這裏是我的xml文件(簡單地說):

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/menu_main_view"> 

<TextView> 
</TextView> 

<LinearLayout> 
    <Button></Button> //couple of buttons 
</LinearLayout> 

</LinearLayout> //this is the parent i guess 

我的第一個猜測是,所有兒童的必須是在1個母,這在我的情況是LinearLayout中。這似乎沒有工作。

感謝

回答

0

是任何查看實例應按照源文件 {}的Android /frameworks/base/core/java/android/view/View.java

只有1父爲了從包裝箱中取出一個視圖實例,你需要做以下的事情:

// View view = ... 
ViewParent parent = view.getParent(); 
if (parent instanceof ViewGroup) { 
    ViewGroup group = (ViewGroup) parent; 
    group.removeView(view); 
} 
else { 
    throw new UnsupportedOperationException(); 
} 

我猜你調用Activity.this.setContentView(R.layout ....)在xml佈局文件上。在這種情況下,LinearLayout視圖的父視圖是另一個LinearLayout由「裝飾窗口」提供的實例。

刪除「裝飾窗口」的唯一孩子往往不是一個好習慣。你最好明確地創建ViewSwitcher的子項:

// Activity.this.setContentView(viewSwitcher); 
// final Context context = Activity.this; 
final android.view.LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
final View layMenu = inflater.inflate(R.layout...., null /* container */); 
final View menuSwitcher = inflater.inflate(R.layout...., null /* container */); 
viewSwitcher.addView(layMenu); 
viewSwitcher.addView(menuSwitcher); 
+0

我很困惑。即我的LevelPicker是一個擴展LinearLayout的自定義類,在構造函數中我調用this.addView(inflater.inflate(R.layout ...)。我該如何正確地做到這一點?還應該是什麼時候做Xml的內容你在上面描述的是什麼? – user717572 2011-12-31 13:42:24

+0

LayoutInflater適用於xml佈局文件,在LevelPicker的情況下,只需簡單地用java new運算符創建實例,或者如果你喜歡,你也可以使用xml文件來描述基於它的UI就像你在xml中使用正常的LinearLayout一樣,唯一的區別是你應該使用LevelPicker的限定名作爲xml標籤,即 chyou 2012-01-02 12:24:40

+0

您在Activity.this.setContentView()調用中使用的任何有效佈局xml文件都可以由LayoutInflater「膨脹」。 – chyou 2012-01-02 12:26:01