无论如何要为特定的视图/视图组使用 XML 布局文件? [英] Anyway to use XML layout files for specific View/ViewGroups?

查看:22
本文介绍了无论如何要为特定的视图/视图组使用 XML 布局文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义 View,我想在 XML 文件中而不是通过代码指定布局.

I have a custom View that I'd like to specify the layout of in an XML file rather than through code.

无论如何我可以获取一个 Android XML 布局文件并使用它来刷新我的自定义 View 的内容?

Is there anyway I can take an Android XML layout file and use it to flush out my custom View's content?

我知道它可以通过 setContentView 方法在 Activity 中完成,但是 Views 似乎没有类似的方法>.

I know it can be done in an Activity via the setContentView method, but there doesn't seem to be a similiar method for Views.

推荐答案

这里是基本概述: 在您的活动代码中,使用 findViewById 获取您要在 XML 中定义的子视图的容器在活动的主视图中.然后,使用 mySubview = getLayoutInflater().inflate(R.layout.mysubview, mycontainerInRootView) 构建新的包含视图.最后,您可以使用返回的子视图 findViewById 将子视图的控件挂钩到主活动中.

Here's the basic overview: In code for your activity, use findViewById to get the container of the subview you want to define in XML in the activity's main view. Then, use mySubview = getLayoutInflater().inflate(R.layout.mysubview, mycontainerInRootView) to build the new contained view. Finally, you can use the returned subviews findViewById to hook the subview's controls into the main activity.

在自定义 View 类中,您同样需要一个 LayoutInflater 实例来为您完成工作,但细节可能会有所不同.我会让自定义 View 成为一个 ViewGroup 子类来启动,然后在构造函数中使用 LayoutInflater.from(ctx) 来获取充气器并从那里开始.它看起来像 mContents = LayoutInflater.from(ctx).inflate(R.layout.mycustomview, this).

In a custom View class, you similarly need to just get a LayoutInflater instance do do the work for you, but the details will probably work out a little differently. I'd make the custom View a ViewGroup subclass to start, then use LayoutInflater.from(ctx) in the constructor to get the inflater and go from there. It would look something like mContents = LayoutInflater.from(ctx).inflate(R.layout.mycustomview, this).

这篇关于无论如何要为特定的视图/视图组使用 XML 布局文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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