Blogger Scott

          The specified child already has a parent. You must call removeView() on the child's parent first.的解決辦法

              出現(xiàn)The specified child already has a parent. You must call removeView() on the child's parent first.這個問題,一般原因是對layout.xml的使用理解不清楚。
              以xml文件方式來設(shè)計界面的布局,如果需要動態(tài)的對xml文件中的各類View進行修改的話,在代碼中使用時,不能直接使用this.findViewById(R.id.***)來獲取xml文件中的每個View,然后再將這些View加入到代碼中的Layout中來進行顯示。正確的做法應(yīng)該是使用inflater。

              舉例如下:
          xml布局文件test.xml為:
           1<?xml version="1.0" encoding="utf-8"?>
           2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
           3    android:orientation="vertical" android:layout_width="fill_parent"
           4    android:layout_height="fill_parent">
           5
           6    <TextView android:id="@+id/tv1" android:layout_gravity="center_vertical"
           7        android:layout_width="wrap_content" android:layout_height="wrap_content"
           8 />
           9
          10    <TextView android:id="@+id/tv2" android:layout_gravity="center_vertical"
          11        android:layout_width="wrap_content" android:layout_height="wrap_content"
          12         />
          13
          14    <TextView android:id="@+id/tv3"
          15        android:layout_gravity="center_vertical" android:layout_width="wrap_content"
          16        android:layout_height="wrap_content"  />
          17
          18    <ImageView android:src="@drawable/line" android:layout_width="fill_parent"
          19        android:layout_height="fill_parent"  />
          20
          21</LinearLayout>


          如果你需要使用這個布局XML文件,并根據(jù)自己的需要,將其中三個TextView的文字做更改,則在代碼中應(yīng)該這樣去使用:
           1     
           2     LayoutInflater inflate = (LayoutInflater)
           3         getSystemService(Context.LAYOUT_INFLATER_SERVICE);
           4         LinearLayout layout = (LinearLayout)inflate.inflate(R.layout.poemshowlist, null); 
           5         
           6         ((TextView)layout.findViewById(R.id.tv1)).setText(text1);
           7         ((TextView)layout.findViewById(R.id.tv2)).setText(text2);
           8         ((TextView)layout.findViewById(R.id.tv3)).setText(text3);
           9         
          10         LinearLayout ll= new LinearLayout(this);
          11         ll.addView(layout);
          12         setContentView(ll);
          13         
          14         
          15





          posted on 2010-12-11 22:28 江天部落格 閱讀(8101) 評論(0)  編輯  收藏 所屬分類: Android

          主站蜘蛛池模板: 漾濞| 门头沟区| 台北市| 吐鲁番市| 邢台市| 阜新| 依安县| 涿州市| 曲周县| 旬阳县| 临泉县| 巫山县| 农安县| 揭东县| 溆浦县| 阳春市| 布拖县| 饶河县| 文登市| 六枝特区| 大庆市| 九寨沟县| 朝阳区| 达尔| 玉龙| 巴彦淖尔市| 赫章县| 荣昌县| 涟源市| 商水县| 方城县| 政和县| 靖江市| 龙川县| 南华县| 个旧市| 辉南县| 临夏县| 定南县| 冷水江市| 合作市|