Android的布局与运行时另一个视图替换视图 [英] Android layout replacing a view with another view on run time

查看:165
本文介绍了Android的布局与运行时另一个视图替换视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML布局文件主要有两个textviews A / B和C.观点 比我有其他两个XML布局文件选项1和选项2。 是否有可能通过Java为加载选项1或选项2的运行时间为C?如果是这样,我一定要使用什么功能?

I have a xml-layout file main with two textviews A/B and a view C. Than 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);

如果您不希望替换已有的视图,但在初始化时选项1 /选项2之间进行选择,那么你可以这样做更容易:设置机器人: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆