2012-03-26 138 views
1

我試圖使用this創建自定義標籤。但是,當我嘗試從充氣佈局創建的TextView的實例,並用它作爲我的TabHost.TabSpec的看法,我收到自定義標籤「指定的孩子已經有父母」

「未處理的異常:

Java.Lang.IllegalStateException:指定的孩子已經有一個父親,你必須先調用孩子父母的removeView()。「

Main.cs

public class Main : TabActivity 
{ 
    protected override void OnCreate(Bundle bundle) 
    { 
     base.OnCreate(bundle); 

     SetContentView(Resource.Layout.Main); 

     Intent[] intents = new Intent[3]; 
     intents[0] = new Intent(this, typeof(Inspection)).PutExtra("Name", "Inspection"); 
     intents[1] = new Intent(this, typeof(Transfer)).PutExtra("Name", "Transfer"); 
     intents[2] = new Intent(this, typeof(ServiceCalls)).PutExtra("Name", "Service Calls"); 

     foreach (var intent in intents) 
     { 
      intent.AddFlags(ActivityFlags.NewTask); 
      TextView tv = getView(intent.GetStringExtra("Name")); 
      TabHost.TabSpec spec = TabHost.NewTabSpec(intent.GetStringExtra("Name")).SetIndicator(tv).SetContent(intent); 
      TabHost.AddTab(spec); 
     } 

     TabHost.CurrentTab = 0; 
    } 

    private TextView getView(string text) 
    { 
     View v = LayoutInflater.Inflate(Resource.Layout.tabs_bg, (ViewGroup)FindViewById(Android.Resource.Id.Content));    
     TextView tv = (TextView)v.FindViewById(Resource.Id.tabsText); 
     tv.Text = text; 

     return tv; 
    } 
} 

tabs_bg.axml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/tabsLayout" android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
    <TextView android:id="@+id/tabsText" android:layout_width="wrap_content" 
    android:layout_height="wrap_content" android:background ="@drawable/tab_selector" 
    android:textSize="18dip"/> 
</LinearLayout> 

如果我更換

TextView tv = (TextView)v.FindViewById(Resource.Id.tabsText); 

在getView與

TextView tv = new TextView(this); 

然後我沒有收到該錯誤。所以它看起來好像與tabs-tab中的tabsText有關,儘管這正是作者在示例中所做的。

回答

3

你是從移植的例子不從createTabView返回TextView的,則返回的LinearLayout。您正在返回電視而不是vgetView

+0

就是這樣。謝謝! – jmease 2012-03-26 20:21:58

0

使用

View v = LayoutInflater.Inflate(Resource.Layout.tabs_bg, null); 
+0

同樣的例外。 – jmease 2012-03-26 19:31:25

相關問題