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?
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.
-
Must I remove the fragment, or will the fragment also be removed? – Karl Morrison Jul 7 '14 at 23:59
-
3@KarlMorrison This question is almost 4 years old and has nothing to do with fragments. I suggest to file a new question and/or take a look at
android.app.FragmentTransaction
and it'sreplace()
method. – lupz Jul 11 '14 at 9:13 -
It is a pity your answer is too complex - in the comments - for novice Android programmers :-( – Antonio Sesto Feb 4 '15 at 21:07
-
2
-
@broot I want to add Images daynamically to my linearlayout that i have done. later I remove some of images from layout. then I want to restore it at its own position from where I have removed. means I want to add images without removing child's parent can you please hlep me ? – PriyankaChauhan Apr 25 '17 at 6:57
And if you do that very often, you could use a ViewSwitcher or a ViewFlipper to ease view substitution.
-
Yes, if there is question of alternate views, then view flipper/switcher is better to use – Zoombie Aug 4 '11 at 15:10
-
8
-
2
-
I know this is old - but the caveat is that a ViewSwitcher initializes and holds both Views in itself (a FrameLayout). – Vikram Bodicherla Apr 13 '18 at 16:35
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);
}