ef2011
ef2011

Reputation: 10631

How to implement LinearLayout.replaceView() -- or ViewGroup.replaceView() in general

Looking at the documentation, there is LinearLayout.addView() but there isn't any LinearLayout.replaceView().

On the other hand, there is LinearLayout.removeView().

Is implementing my own LinearLayout.replaceView() as two simple successive calls to remove+add safe enough? i.e. are there caveats to watch for?

public void replaceView(View oldView, View newView) {
   removeView(oldView);
   addView(newView);
}

Upvotes: 1

Views: 868

Answers (1)

OcuS
OcuS

Reputation: 5310

Try this:

public void replaceView(final View oldView, final View newView) {
    addView(newView, indexOfChild(oldView));
    removeView(oldView);
}

Upvotes: 3

Related Questions