Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace view programmatically in Android? [duplicate]

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 :(

like image 976
AlikElzin-kilaka Avatar asked Jun 12 '13 10:06

AlikElzin-kilaka


1 Answers

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?

like image 90
britzl Avatar answered Nov 20 '22 11:11

britzl