Skip to content

Instantly share code, notes, and snippets.

@magmastonealex
Last active August 10, 2016 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magmastonealex/4656db0967b6d5e4f8fe112fa02c0a70 to your computer and use it in GitHub Desktop.
Save magmastonealex/4656db0967b6d5e4f8fe112fa02c0a70 to your computer and use it in GitHub Desktop.
A small program to generate Android layout initializers from XML.

Parses an Android layout XML file iteratively, getting every element with an explicit id.

Then creates private variables, and separately the initializers for each one, with an appropriate cast in place.

Greatly lowers time to convert layout -> finished custom view.

Pass as first parameter the path to a layout.xml. All output is on stdout.

import lxml.etree as ET
import sys
defs=[]
binds=[]
for event, element in ET.iterparse(open(sys.argv[1])):
try:
elid = element.attrib["{http://schemas.android.com/apk/res/android}id"]
elid = elid.split("/")[-1]
elid_transform = elid.split(".")[-1]
elid_find = elid.replace(".","_")
eltype = element.tag.split(".")[-1]
defs.append("private "+eltype+" "+elid_transform+";")
binds.append(elid_transform +" = ("+eltype+") inflatedView.findViewById(R.id."+elid_find+");")
except:
pass
print "\n".join(defs)
print "----"
print "\n".join(binds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment