Dynamically inflates UI in Android App
2015-12-10 01:29
447 查看
Dynamically inflates UI in Android App
There is a fascinating idea that inflates UI according to an android layout xml downloaded from server. According to the Android API, it looks quite feasible.One of
LayoutInflate.inflatemethod
overloads accept Layout Xml as
XmlPullParser.
And
XmlPullParsercan
wrap around an input stream, so as consequence, following code seems to be working:
Inflate view on the fly
123456789101112131415161718192021 | public class DynamicView extends FrameLayout { public DynamicView(Context context, InputStream layoutData) throws XmlPullParserException { super(context); createView(context, layoutData); } private void createView(Context context, InputStream layoutData) throws XmlPullParserException { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser parser = factory.newPullParser(); parser.setInput(layoutData, "UTF-8"); inflater.inflate(parser, this, true); }} |
According to the LayoutInflater document, this approach won’t work(at least for now, it won’t).
For performance reasons, view inflation relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not currently possible to use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
LayoutInflater Documentdeveloper.android.com
Actually, Android compiler compiles the layout xml files into binary xml block, which has convert attributes into some special format. And in Android SDK, the
LayoutInflateruses
XmlResourceParserinstead
of plain
XmlPullParser,
which is created by
XmlBlock.
XmlBlockis an
internal class used in
Resourcesto
cache the binary xml document.
And there is no way to create XmlResourceParser or other classes to inject custom behavior into this process. Personally assume that it is pretty much related to the Android Resource and Theming mechanism, there are quite a number cross references between resources.
To make it works in a efficient way, Android Runtime did a lot work, such as cache and pre-processing. To override this behavior require quite a number of work and need to aware of potential performance issue. Since the inflating could happen quite often during
navigation.
As a not that fansy alternative, UI based on HTML hosted in WebView could be considered.
转自:http://timnew.me/blog/2013/12/13/dynamically-inflates-ui-in-android-app/
相关文章推荐
- Android开源项目集合
- .9图设为背景时被放大、变形的原因
- Android之Adapter用法总结
- 解决Android GridView行高问题
- kobject和uevent的一点想法--待续
- Application类的使用范例
- Java版 微信红包算法
- Retrofit基础入门(1)
- ARC转换
- 喝酒不骑马的Android自学日记(1)
- 安卓无标题主题风格设置
- Android自定义控件
- IOS开发中的微信支付
- 6-读书笔记----iOS开发指南:从零基础到App Store上架--iOS-iPhone与iPad应用开发的差异和iOS分层架构设计
- Android动画浅析
- iOS- 如何集成支付宝
- IOS银联支付的流程
- Android5.0Palette
- Android5.0水波纹效果ripple实现
- Android5.0水波纹效果ripple实现