膨胀 xml 文件或在循环中创建新的 View 实例?
我正在创建一个 screen/xml,其中包含:
- TextView (标题)
- LinearLayout (包含大量relativelayout 的占位符)
我需要添加许多 RelativeLayout
(包含两个 TextViews) 到循环中的
LinearLayout
(上面提到的)。这基本上是 RelativeLayouts
列表。我有两种方法可以做到这一点:
- 创建一个 xml 文件,其中包含
RelativeLayout
(以及其下的两个TextViews
)。在代码中一次又一次地膨胀它(在循环中)。然后将其添加到上面提到的LinearLayout
中。 - 使用关键字“new”创建
RelativeLayout
和TextView
的实例。并将实例添加到上面提到的LinearLayout
中。
这是最便宜的方式。
I am creating a screen/xml which has:
- TextView (Header)
- LinearLayout (placeholder to contain numerous RelativeLayouts)
I need to add many RelativeLayout
(containing two TextView
s) to the LinearLayout
(mentioned above) in loop. This basically would be list of RelativeLayouts
. I have two ways doing this:
- Create an xml file which has the
RelativeLayout
(and twoTextViews
under it). Inflate this in the code again and again( in loop).And then add this toLinearLayout
mentioned above. - Create the instance of
RelativeLayout
andTextView
using the keyword "new". And add the instances to the above mentionedLinearLayout
.
Which is the least expensive way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该采用#1 方法 - 从 xml 文件膨胀布局。这是因为最好将代码与 UI 分开。您可以使用 ADT 工具更轻松地预览和重新设计您的 xml,您可以稍后出于类似目的重用此 xml,等等。
虽然创建 UI 的代码难以阅读和维护,并且仅使用代码很难设计出合适的 UI。
一般来说,最好在 xml/资源中保留尽可能多的 UI 相关内容。当更容易使用代码(例如创建 10 个具有相同文本的按钮)或唯一的方法(例如动态生成一些视图)时,可以回退到代码。
You should go with #1 approach - inflate layout from xml file. That's because its better to keep your code separate from your UI. You can preview and redesign your xml much easier using ADT tools, you can reuse this xml later for similar purposes and so on.
While code that creates UI is hard to read and hard to maintain, and its hard to design a proper UI using code only.
In general, its better to keep as much UI related stuff in xmls/resources. And fall back to code when its easier to use code (like creating 10 buttons with same text) or the only way to go (like dynamically generating some views).