1

ViewSwitcher があり、それにビューを追加したい:

    // initialize views
    final ViewSwitcher switcher = new ViewSwitcher(this);
    layMenu = (LinearLayout)findViewById(R.id.menu_main_view);
    final LevelPicker levelPicker = new LevelPicker(getApplicationContext());   

    (//)switcher.addView(layMenu);
    (//)switcher.addView(findViewById(R.layout.menu_switcher));

1 つはカスタム ビューで、もう 1 つは XML からのものです。そのうちの1つにコメントしましたが、どちらも投げているようですIllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

ビューを最初に「コンテナ」に入れる(別のレイアウト)、またはremoveView((View)getParent)を試したなど、いくつかのことを試しました.logcatが言おうとしていると思います..

これが私のxmlファイルです(一言で言えば):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/menu_main_view">

<TextView>
</TextView>

<LinearLayout>
    <Button></Button> //couple of buttons
</LinearLayout>

</LinearLayout> //this is the parent i guess

私の最初の推測では、すべての子は 1 つの親 (私の場合は LinearLayout) に属している必要がありました。これはうまくいかなかったようです。

ありがとう

4

1 に答える 1

0

はい、ソースファイル {android}/frameworks/base/core/java/android/view/View.javaによると、View インスタンスは 1 つの親のみを持つ必要があります。

コンテナーから View インスタンスを削除するには、次のことを行う必要があります。

// View view = ...
ViewParent parent = view.getParent();
if (parent instanceof ViewGroup) {
    ViewGroup group = (ViewGroup) parent;
    group.removeView(view);
}
else {
    throw new UnsupportedOperationException();
}

xml レイアウト ファイルでActivity.this.setContentView(R.layout....)を呼び出したと思います。この場合、LinearLayoutビューの親は、「装飾ウィンドウ」によって提供される別のLinearLayoutインスタンスでした。

「装飾ウィンドウ」の唯一の子を削除することは、多くの場合、良い習慣ではありません。ViewSwitcher の子を明示的に作成することをお勧めします。

// Activity.this.setContentView(viewSwitcher);
// final Context context = Activity.this;
final android.view.LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layMenu = inflater.inflate(R.layout...., null /* container */);
final View menuSwitcher = inflater.inflate(R.layout...., null /* container */);
viewSwitcher.addView(layMenu);
viewSwitcher.addView(menuSwitcher);
于 2011-12-31T02:05:53.937 に答える