Load layout created by user
I'm trying to load an XML file created by user to use it in my app. I know that it's not possible to use the XML file as a resource because the layout files are compiled in building APK process. Is there anyway to use/create/load layouts on-the-fly outside the layout folder?
You cannot inflate arbitrary XML because XML files in Android projects get processed at build time and converted to a binary format. In other words, you can only build the layouts programmatically with the Java APIs.
What you can do is parse the user's file with a standard XML parser (eg XmlPullParser
and build the views yourself. Basically you would be re-implementing LayoutInflater
, which you can find the source code for online.
One thing to note is the user's XML won't be able to refer to resources at all. For example, they could not do something like android:textColor="@color/some_color"
. The build processing turns references like these into pointers to resource values, whereas if you were to simply read this in plain XML, it would just be the text "@color/some_color"
.
Perhaps instead of allowing users to create full-fledged Android layout XMLs, you should instead choose a limited subset of things you will support and define a simpler way of describing these custom layouts. Then you wouldn't have to use XML, you can define a custom "language" with just the things you want. This way you can limit the users to relatively simple APIs, like text color; you simply map some field defined in your custom language to a call to textView.setTextColor()
.
You can create a XmlPullParser from your file and pass it to the layout inflater.
To create the XMLPullParser from your file you can follow this example: https://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
And after having the XMLPullParser object, you can call this method: https://developer.android.com/reference/android/view/LayoutInflater.html#inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup)
You need an ViewGroup that will be the parent of the view. If you need the view to be an activity, I recommend that you create a empty activity with a layout and add the parsed layout to the empty layout. Don't try to inflate the layout without a parent, you can have distinct results in different devices.
链接地址: http://www.djcxy.com/p/62800.html下一篇: 加载由用户创建的布局