How to replace view programmatically in Android? [

2019-03-27 21:27发布

问题:

This question already has an answer here:

  • Android layout replacing a view with another view on run time 3 answers

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

回答1:

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?