11

I have a complex view, containing several subviews, like text views and image views. I'd like to replace one of the image views with another (derived) image view (the other one support loading images in the background).

How can I replace the original image view with a new one?

The solution I currently have is just copy pasting the whole XML layout and do the replace in the new XML - Very bad to duplicate and not reuse things :(

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277

1 Answers1

35

I'm not really sure that I understand what you're saying but if you simply wanna remove one instance of View from a layout and exchange it with another you could use a utility class like this:

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're saying "Very bad to duplicate and not reuse"? Are you aware of the include tag?

britzl
  • 10,132
  • 7
  • 41
  • 38
  • Regrading the followup, `include` is good when you want to add an existing layout to a another one. Here, I want to replace a view within another - programmatically - not compile time. – AlikElzin-kilaka Jun 12 '13 at 11:15
  • 2
    Small addition: before adding `newView` to the parent in `replaceView`, it might be useful to copy the currentViews id: `newView.setId(currentView.getId());` so that `findViewById` returns `newView` – Frederic Klein Sep 06 '16 at 19:48
  • Is it me or the `index` is for `LinearLayout` and you will need to do something different for `RelativeLayout`: `newView.setLayoutParams(currentView.getLayoutParams());`. Another thing that will be missed in regards to @FredericKlein `id` is the `onClick`. – MikeL Nov 01 '18 at 15:05