0

Программа вылетает после второго нажатия кнопки "btnAdd", не могу понять в чем проблема

public class MainActivity extends AppCompatActivity {

LinearLayout view;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
ArrayList<TextView> textViews;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textViews = new ArrayList<TextView>(10);
    // создаем view из dialog.xml
    view = (LinearLayout) getLayoutInflater()
            .inflate(R.layout.dialog, null);
}

public void onclick(View v) {
    AlertDialog.Builder adb = new AlertDialog.Builder(this);
    adb.setTitle("Custom dialog");
    // устанавливаем ее, как содержимое тела диалога
    adb.setView(view);
    // находим TexView  для отображения кол-ва созданных TextView и времени
    TextView tvCount = (TextView) view.findViewById(R.id.tvCount);
    TextView tvTime = (TextView) view.findViewById(R.id.tvTime);
    tvTime.setText(sdf.format(new Date(System.currentTimeMillis())));
    switch (v.getId()){
        case R.id.btnAdd:
            TextView tv = new TextView(this);
            view.addView(tv,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
            tv.setText("TextView " + (textViews.size()+1));
            textViews.add(tv);
            break;
        case R.id.btnRemove:
            if (textViews.size() > 0){
                TextView tv1 = textViews.get(textViews.size()-1);
                view.removeView(tv1);
                textViews.remove(tv1);
            }
            break;
    }
    tvCount.setText("Кол-во TextView = " + textViews.size());

    adb.show();
}}
2
  • 3
    покажите стэктрейс с ошибкой.
    – UjinUkr
    12 ноя 2018 в 22:04
  • @UjinUkr в ответ кинул 13 ноя 2018 в 7:43

1 ответ 1

0

Решил проблему удалением родительской разметки элемента. Только я не совсем понял, на каком участке кода эта родительская разметка присваивается элементу и почему программа выдает ошибку, если разметку не убрать.

public void onclick(View v) {
    AlertDialog.Builder adb = new AlertDialog.Builder(this);
    adb.setTitle("Custom dialog");
    TextView tvCount = (TextView) view.findViewById(R.id.tvCount);
    TextView tvTime = (TextView) view.findViewById(R.id.tvTime);

    switch (v.getId()){
        case R.id.btnAdd:
            TextView tv = new TextView(this);
            view.addView(tv, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            tv.setText("TextView " + (textViews.size()+1));
            textViews.add(tv);
            break;
        case R.id.btnRemove:
            if (textViews.size() > 0){
                TextView tv1 = textViews.get(textViews.size()-1);
                view.removeView(tv1);
                textViews.remove(tv1);
            }
            break;
    }

    if(view.getParent()!=null) 
        ((ViewGroup)view.getParent()).removeView(view); // <===== FIX

    adb.setView(view);
    tvCount.setText("Кол-во TextView = " + textViews.size());
    tvTime.setText(sdf.format(new Date(System.currentTimeMillis())));
    adb.show();
}

Вот стэк трейс с ошибкой: введите сюда описание изображения

Ваш ответ

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

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