Android 布局在运行时用另一个视图替换一个视图 [英] Android layout replacing a view with another view on run time
问题描述
我有一个 xml
布局文件 main,其中包含两个文本视图 A/B 和一个视图 C.我还有另外两个 xml
布局文件 option1
和 option2
.是否可以在运行时通过 Java 将 option1
或 option2
加载到 C 中?如果是这样,我必须使用什么功能?
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);
如果你不想替换已经存在的View,而是在初始化时选择option1/option2,那么你可以更容易地做到这一点:设置android:id
对于父布局,然后:
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);
您必须根据视图结构将索引"设置为适当的值.您还可以使用 ViewStub:将 C 视图添加为 ViewStub,然后:
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();
这样,如果您想重构 XML 布局,就不必担心上面的索引"值.
That way you won't have to worry about above "index" value if you will want to restructure your XML layout.
这篇关于Android 布局在运行时用另一个视图替换一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!