Search code examples
androidandroid-imageview

Remove ImageView programmatically from custom Layout


I use FlowLayout. I have here such a button outside.

enter image description here

Pressing the button in the layout adds the same picture as many times as the button is pressed. I figured out how to add a picture, but how to delete a picture?

numberButton.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() {
        @Override
        public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) {
            // Добавляем новый ImageView
            if (oldValue < newValue) {
                ImageView imageView = new ImageView(CreateNewTripActivity.this);
                imageView.setImageResource(R.drawable.i_travel_logo_1);
                ViewGroup.LayoutParams imageViewLayoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                imageViewLayoutParams.height = 300;
                imageViewLayoutParams.width = 300;
                imageView.setLayoutParams(imageViewLayoutParams);
                imageView.setId();
                flowLayout.addView(imageView);
            } else {
                //Удаляем
                AlertDialog.Builder ad = new AlertDialog.Builder(CreateNewTripActivity.this);
                ad.setTitle(getResources().getString(R.string.title_delete_person));  // заголовок
                ad.setMessage(getResources().getString(R.string.dialog_aushure)); // сообщение
                ad.setPositiveButton(getResources().getString(R.string.button_ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        Toast.makeText(CreateNewTripActivity.this, "Вы сделали правильный выбор",
                                Toast.LENGTH_LONG).show();

                        //TO DO.......
                        flowLayout.removeView(imageView);
                    }
                });
                ad.setNegativeButton(getResources().getString(R.string.button_cancel), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        Toast.makeText(CreateNewTripActivity.this, "Возможно вы правы", Toast.LENGTH_LONG)
                                .show();
                    }
                });
                ad.setCancelable(false);

            }
        }
    });

Solution

  • To delete the last ImageView added to your FlowLayout, you just need to do this:

    flowLayout.removeViewAt(flowLayout.getChildCount() - 1);