Sunday, March 04, 2012

layout.xml -> Activity.java

I made a bunch of changes to a layout file this morning and wished I had a quick way to get all of those elements into my java code so I could make it go. So I popped into Emacs and wrote a little function to do it! And here it is. Enjoy!
(defun xml-to-java ()
  (interactive)
  (progn
    (setq tmp (buffer-string))
    (switch-to-buffer "tmp")
    (insert tmp)
    (goto-char (point-min))
    (save-excursion
      (replace-regexp "[\n\t ]+" " ")
      )
    (save-excursion
      (replace-regexp
       " *<\\(\\w+\\)[^>]*android:id=\"@\\+id/\\(\\w+\\)\"[^>]*>"
       "\nprivate \\1 \\2;\n\\2 = (\\1) findViewById(R.id.\\2);\n")
      )
    (save-excursion
      (replace-regexp " *<!-- \\([^>]*\\) -->" "\n/* \\1 */\n")
      )
    (save-excursion
      (replace-regexp " *<[^>]*>" "")
      )
    (save-excursion
      (replace-string "\n\n" "\n")
      )
    )
  )

No comments: