Create, store and inflate custom layout in runtime

2019-03-19 12:06发布

问题:

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?

回答1:

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.