Android layout replacing a view with another view on run time

AndroidXmlAndroid LayoutView

Android Problem Overview


I have a xml-layout file main with two textviews A/B and a view C. I have two other xml-layout files option1 and option2. Is it possible to load either option1 or option2 in run time via Java into C? If so, what function do I have to use?

Android Solutions


Solution 1 - Android

You could replace any view at any time.

int optionId = someExpression ? R.layout.option1 : R.layout.option2;

View C = findViewById(R.id.C);
ViewGroup parent = (ViewGroup) C.getParent();
int index = parent.indexOfChild(C);
parent.removeView(C);
C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

If you don't want to replace already existing View, but choose between option1/option2 at initialization time, then you could do this easier: set android:id for parent layout and then:

ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
View C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

You will have to set "index" to proper value depending on views structure. You could also use a ViewStub: add your C view as ViewStub and then:

ViewStub C = (ViewStub) findViewById(R.id.C);
C.setLayoutResource(optionId);
C.inflate();

That way you won't have to worry about above "index" value if you will want to restructure your XML layout.

Solution 2 - Android

And if you do that very often, you could use a ViewSwitcher or a ViewFlipper to ease view substitution.

Solution 3 - Android

private void replaceView(View oldV,View newV){
    	ViewGroup par = (ViewGroup)oldV.getParent();
    	if(par == null){return;}
    	int i1 = par.indexOfChild(oldV);
    	par.removeViewAt(i1);
    	par.addView(newV,i1);
    }

Solution 4 - Android

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristianView Question on Stackoverflow
Solution 1 - AndroidbrootView Answer on Stackoverflow
Solution 2 - AndroidSnicolasView Answer on Stackoverflow
Solution 3 - AndroidKaiwalya RangleView Answer on Stackoverflow
Solution 4 - Androidch13mobView Answer on Stackoverflow