Add and Remove Views in Android Dynamically? Ask Question

Add and Remove Views in Android Dynamically? Ask Question

How do I add and remove views such as TextViews from Android app like on the original stock Android contacts screen where you press a small icon on the right side of a field and it adds or deletes a field which consists of a TextView and an editTextView (from what I can see).

Any examples on how to achieve this?

ベストアンサー1

ViewParents in general can't remove views, but ViewGroups can. You need to cast your parent to a ViewGroup (if it is a ViewGroup) to accomplish what you want.

For example:

View namebar = View.findViewById(R.id.namebar);
((ViewGroup) namebar.getParent()).removeView(namebar);

Note that all Layouts are ViewGroups.

おすすめ記事