How to replace viewing programmatically on Android?

I have a complex view containing several subheadings such as text presentations and images. I would like to replace one of the images with another (derived) image (the other supports loading images in the background).

How to replace the original image with a new one?

The solution I currently have is simply to copy the paste of the whole XML layout and do the replacement in the new XML. Duplicating and not reusing is very bad :(

+6
source share
1 answer

I'm not sure I understand what you're saying, but if you just want to remove one instance of the View from the layout and exchange it with another, you can use the utility class as follows:

import android.view.View; import android.view.ViewGroup; public class ViewGroupUtils { public static ViewGroup getParent(View view) { return (ViewGroup)view.getParent(); } public static void removeView(View view) { ViewGroup parent = getParent(view); if(parent != null) { parent.removeView(view); } } public static void replaceView(View currentView, View newView) { ViewGroup parent = getParent(currentView); if(parent == null) { return; } final int index = parent.indexOfChild(currentView); removeView(currentView); removeView(newView); parent.addView(newView, index); } } 

Follow-up question: what do you mean when you say "Very bad to duplicate and not reuse"? Do you know the include tag ?

+24
source

Source: https://habr.com/ru/post/947099/


All Articles