0

私はこのコードを持っており、RelativeLayout( RelativeLayout->ScrollView->LinearLayout->My ChechBoxes) 内にネストされた ScrollView 内にネストされた LinearLayout 内に CheckBoxes を動的に追加したい

li = (RelativeLayout) findViewById(R.id.mainlayout);    
ScrollView sv = new ScrollView(this);
final LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
li.addView(sv);
sv.addView(ll);
for(int i = 0; i < 20; i++) {
    CheckBox cb = new CheckBox(getApplicationContext());
    cb.setText("I'm dynamic!");
    ll.addView(cb);
}
this.setContentView(sv);

しかし、私はこのエラーが発生します:

03-12 20:32:14.840: E/AndroidRuntime(945): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

XML ファイルで既に宣言されている RelativeLayout は、これをどのように修正できますか?

4

2 に答える 2

2
this.setContentView(sv);

これは ScrollView を FrameLayout に追加しようとしますandroid.R.id.contentが、すでにli親を作成していますsv...したがって、「指定された子にはすでに親があります。」

this.setContentView(sv);ScrollView(など)をRelativeLayoutに追加したいだけで、既存のレイアウト全体を置き換えたくないように見えるので、削除できると思います。

于 2013-03-12T20:54:03.120 に答える
0

これを確認してくださいhttp://developer.android.com/training/animation/screen-slide.html サンプルアプリをダウンロードしたら、LayoutChangesActivity.java

以下はアイテムを追加するコードです。

private void addItem() {
    // Instantiate a new "row" view.
    final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(
            R.layout.list_item_example, mContainerView, false);

    // Set the text in the new row to a random country.
    ((TextView) newView.findViewById(android.R.id.text1)).setText(
            COUNTRIES[(int) (Math.random() * COUNTRIES.length)]);

    // Set a click listener for the "X" button in the row that will remove the row.
    newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Remove the row from its parent (the container view).
            // Because mContainerView has android:animateLayoutChanges set to true,
            // this removal is automatically animated.
            mContainerView.removeView(newView);

            // If there are no rows remaining, show the empty view.
            if (mContainerView.getChildCount() == 0) {
                findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
            }
        }
    });

    // Because mContainerView has android:animateLayoutChanges set to true,
    // adding this view is automatically animated.
    mContainerView.addView(newView, 0);
}
于 2013-03-12T21:38:12.730 に答える