0

em get java.lang.IllegalStateException:指定された子にはすでに親があります。最初に子の親でremoveView()を呼び出す必要があります。

どのビューを削除する必要があるかを見つけることができないので、どんな助けでも本当に役に立ちます。

これがコードスニペットです

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:id="@+id/mainLayout"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

</RelativeLayout>

data.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</RelativeLayout>

アクティビティコード

public class ToDo extends Activity {
    /** Called when the activity is first created. */
    Button addNew;
    RelativeLayout mainLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mainLayout=(RelativeLayout)findViewById(R.id.mainLayout);

        RelativeLayout rel;
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        for(int idx=0;idx<2;idx++){
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

            rel = (RelativeLayout) inflater.inflate(R.layout.data,null);
            params.setMargins(0, 50, 0, 0);

             TextView fromWeb= (TextView) rel.findViewById(R.id.txt);
             fromWeb.setText("AA");

             mainLayout.addView(rel,params);
        }

    }
}
4

1 に答える 1

0

以下のコードは正しくありません:

TextView fromWeb= (TextView) rel.findViewById(R.id.txt);
fromWeb.setText("AA");
rel.addView(fromWeb,params); // the TextView is alredy in the rel RelativeLayout!
mainLayout.addView(rel);

すでにレイアウトファイルにあるものを(メソッドを使用して)再度追加しているためです(以前にで検索したように)。代わりに、次のようになります。addViewTextViewfindViewById

TextView fromWeb= (TextView) rel.findViewById(R.id.txt);
fromWeb.setText("AA");
mainLayout.addView(rel);  

マージンが必要な場合TextViewは、レイアウトファイルに設定します。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="TextView" />

</RelativeLayout>
于 2012-10-15T07:40:41.390 に答える