分享

Create, store and inflate custom layout in runtime

 quasiceo 2015-07-01

I'm trying to find a solution for the following problem. The application I work on requires a possibility for user to produce custom UI (layout of simple widgets) via custom UI builder. So, user may stack widgets (images, mostly. But TextViews and EditText, as well) on canvas, move them around, etc. UI have to be stored in a database for future use. So, there should be some mechanism for loading and inflating of this UI. This is the main problem.

My first idea was to rely on standard Android layout mechanism. Unfortunately, the LayoutInflater works with XML compiled into a binary form. And as far as I know, it's not possible to compile an XML string into binary representation in runtime.

Does, anybody have experience with such problem? Any suggestions?

asked Apr 5 '11 at 14:48
Anton
1,23131429

    
    
considering that you will be implementing some subset of the layout functionality in your editor it may make sense to roll your own representation anyway. –  Matthew Willis Apr 5 '11 at 16:12

1 Answer

Check out the inflate methods of LayoutInflater. You can actually give it any XmlPullParser to use as its source, which in turn can be constructed given any Reader.

In other words, you can use just about any character stream as your xml source for inflating.

The beginning of the XmlPullParser docs gives you the basic outline for creating the pull parser:

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader("<foo>Hello World!</foo>"));

Update - this isn't going to work, as mentioned in the LayoutInflater docs.

answered Apr 5 '11 at 14:53
Matthew Willis
30.8k56870

    
This doesn't work with xml layouts actually. If you pass a simple XML to XmlPullParser, and then try to call inflater.inflate(xpp, null) method, it will throw you an exception –  Anton Apr 5 '11 at 14:59
2  
And the reason is - the LayoutInflater itself uses XmlBlock.Parser, a parser created to work with binary from of xml layouts. While XmlPullParserFactory creates an instance of simple org.kxml2.io.KXmlParser –  Anton Apr 5 '11 at 15:02
    
I stand corrected! Thank you for pointing that out. Then, this is a duplicate of /questions/1942104/… –  Matthew Willis Apr 5 '11 at 15:11
    
Yes, seems like a duplicate. It's so strange that there's no facility available to inflate layout from a string... Even if the performance is not good, so what?.. –  Anton Apr 5 '11 at 15:16
    
Do it in Java then. Parse the XML, and then create the necessary Views with the required properties. Then let us know how it performs ;) –  Joseph Earl Apr 5 '11 at 16:11

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多