replace View with a new View - Android User Interface

Android examples for User Interface:View

Description

replace View with a new View

Demo Code


//package com.java2s;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Main {
    public static View replaceView(LayoutInflater inflater,
            View currentView, int newViewId) {
        View newView = inflater.inflate(newViewId, null);
        return replaceView(inflater, currentView, newView);
    }//  w  ww  .jav  a  2s. c om

    public static View replaceView(LayoutInflater inflater,
            View currentView, View newView) {
        ViewGroup parent = getParent(currentView);
        if (parent == null) {
            return null;
        }
        final int index = parent.indexOfChild(currentView);
        removeView(currentView);
        parent.addView(newView, index);
        return newView;
    }

    public static ViewGroup getParent(View view) {
        return (ViewGroup) view.getParent();
    }

    public static void removeView(View view) {
        if (view != null) {
            ViewGroup parent = getParent(view);
            if (parent != null) {
                parent.removeView(view);
            }
        }
    }
}

Related Tutorials