removeView导致所有视图消失

时间:2015-03-26 04:06:48

标签: android alertdialog

在下面的代码中,我将TextView添加到alertDialog中并将其删除(由两个按钮控制)。添加工作正常,但删除删除所有以前添加的TextView' s。为什么会发生这种情况而不仅仅删除最近的TextView?

final int DIALOG_ADD = 1;
final int DIALOG_REMOVE = 2;

LinearLayout view;
ArrayList<TextView> textViews;

@Override
protected Dialog onCreateDialog(int id) {
    AlertDialog.Builder adb = new AlertDialog.Builder(this);
    adb.setTitle("Custom dialog");

    view = (LinearLayout)getLayoutInflater().inflate(R.layout.dialog, null);

    adb.setView(view);
    return adb.create();

}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {

    super.onPrepareDialog(id, dialog);

    switch (id) {

    case DIALOG_ADD:
        TextView tv = new TextView(this);
        tv.setText("TextView " + textViews.size());
        view.addView(tv,new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
        textViews.add(tv);

        break;

    case DIALOG_REMOVE:

        TextView tv1 = textViews.get(textViews.size() - 1);
        view.removeView(tv1);
        textViews.remove(tv1);

        break;

    };

    TextView tvCount = (TextView)dialog.getWindow().findViewById(R.id.tvCount);
    tvCount.setText("Text view count: " + textViews.size());

}

1 个答案:

答案 0 :(得分:0)

试试这样:

view.removeViewAt(textViews.size() - 1);

而不是

view.removeView(tv1);