0

Есть динамически созданный LinearLayoyt. Мне нужно добавить его в LinearLayout, объявленный в xml разметке. Причем не один раз, а н-ное количество. Меня немного удивило, что оказывается нельзя просто взять и добавить леяут в леяут несколько раз. При повторном клике на кнопку приложение вылатает с ошибкой. Все наверно догадались, что там в стектрейсе: The specified child already has a parent. You must call removeView() on the child's parent first. Мне просто жизненно необходимо добавить леяут в леяут. Как это можно реализовать?

public class MyActivity extends Activity {
/**
 * Called when the activity is first created.
 */

LinearLayout lin;

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

    lin = (LinearLayout)findViewById(R.id.Layout);

    final LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

    Button b1 = new Button(this);
    b1.setText("Knopka");
    b1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

    layout.addView(b1);

    Button button = (Button)findViewById(R.id.Button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          lin.addView(layout);
        }
    });

}
}

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

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="SimpleTest"
    android:id="@+id/Button"
    />

<LinearLayout

        android:id="@+id/Layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"

    />
</LinearLayout>

1 ответ 1

3

Вы каждый раз пытаетесь добавить один и тот же Layout, в первый раз прокатывает, а во второй раз ваш лейаут уже имеет родителя. Создавайте каждый раз новый лейаут и пихайте на здоровье:

@Override        
public void onClick(View v) {
   lin.addView(new Layout(...));        
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.