我尝试使用this创建自定义标签。但是,当我尝试从膨胀的布局创建TextView的实例并将其用作TabHost.TabSpec中的View时,我收到了

“未处理的异常:

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_bg中的tabsText有一定关系,尽管这正是作者在示例中所做的方式。

最佳答案

您要移植的示例不会从createTabView返回TextView,而是返回LinearLayout。您正在getView中返回电视而不是v。

关于android - 自定义标签“指定的 child 已经有 parent ”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9878437/

10-12 04:18