简体   繁体   中英

how to remove dynamically inflated views?

In a simple card game that i want to develop, I have three buttons: button1,button2 and button3. button1 creates two imageviews in a tablerow and displays the image. When button2 and/or button3 is clicked, it dynamically adds imageview on the tablerow through layout inflater. When game is over, I want user to click button1 and start things all over again. I am able to do that but the problem is, the imageviews that were previously displayed by clicking button2 and button3 also displays. I want them to be removed when button1 is clicked. How can I remove them on click of button1? Please help me!

Just like you added views, you can remove them. Just call removeViewAt(int index) or removeView(View view) on the parent container to remove the view(s) you want.

Alternatively, if you foresee reusing them, you can just set their visibility to GONE . Then you could bring them back without the expense of inflating them again.

If you're letting the inflater automatically attach the inflated imageviews to the parent, then you'll have to keep track of the position of the added views. You can use getChildCount on the parent just before inflating to find the index of the next view that will be added.

you can use ViewGroup.removeView(View v);

something like this:

tblRow.removeView(button2);

here is how I add then remove a View 5 seconds later (in another context)

  final LinearLayout linearLayout = context.getResources().getLayout(R.layout.activity_main)
  LayoutInflater inflater = LayoutInflater.from(linearLayout.getContext());
  final View details = inflater.inflate(R.layout.extra_details, linearLayout, false);
  linearLayout.addView(details);

  new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (linearLayout.findViewById(R.id.extra_details) != null){
                        linearLayout.removeView(details);
                    }
                }
            }, 5000);

the same use scenario is in the context of onClickListener. Check more here https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

//add view

LayoutInflater inflater = (LayoutInflater)this.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
final View buttons = inflater.inflate(R.layout.activity, null );
addContentView(buttons, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

//remove view

((ViewManager)buttons.getParent()).removeView(buttons);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM