自定义标签“指定的孩子已经有父母”
问题描述:
我试图使用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有关,尽管这正是作者在示例中所做的。
答
你是从移植的例子不从createTabView返回TextView的,则返回的LinearLayout。您正在返回电视而不是v在getView。
答
使用
View v = LayoutInflater.Inflate(Resource.Layout.tabs_bg, null);
+0
同样的例外。 – jmease 2012-03-26 19:31:25
就是这样。谢谢! – jmease 2012-03-26 20:21:58