The layout in Android turns into Java code

Source: Internet
Author: User

Android always assigns an ID to the control, and then writes a control name in the code, which in itself is manual work. Here I wrote a small code generation tool class that generated the anroid XML layout file As a Java file through the console output. Support for Findviewbyid mode, and Xutils mode at the same time. The parsing of XML is used in the pull parser. A jar file is already included in the demo. As an example:

Suppose there's a layout file named Empty.xml.

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "              android:id=" @+id/empty "              android:layout_width=" match_parent "              android:layout_height=" Match_ Parent "              android:gravity=" center ">    <progressbar android:id=" @+id/loading_pb "                 android:layout_ Width= "Wrap_content"                 android:layout_height= "wrap_content"                 style= "@android: style/ Widget.ProgressBar.Small.Inverse "/>    <textview android:id=" @+id/tv_loading "              android:layout_width=" Wrap_content "              android:layout_height=" wrap_content "              android:layout_torightof=" @+id/loading_pb              " android:text= "Loading ..."/></linearlayout>



The name of the control generated by the ID is directly output through my tool class Xmlgen.java. Copy it from the console to the code.

Import Org.xmlpull.v1.xmlpullparser;import Org.xmlpull.v1.xmlpullparserexception;import Org.xmlpull.v1.xmlpullparserfactory;import Java.io.bytearrayinputstream;import Java.io.File;import Java.io.fileinputstream;import java.io.ioexception;import Java.io.inputstream;import java.util.ArrayList;/** * Pass in an XML string and convert to */public class XMLGen {private static string xml = "<?xml version=\" 1.0\ "encoding=\" utf-8\ "? >\n" + "\ N "+" <linearlayout xmlns:android=\ "http://schemas.android.com/apk/res/android\" \ n "+" android:id=\ "@+id/em Pty\ "\ n" + "android:layout_width=\" match_parent\ "\ n" + "android:layout_height=\" match_parent\ "\ n                 "+" android:gravity=\ "Center\" >\n "+" <progressbar android:id=\ "@+id/loading_pb\" \ n "+"                 Android:layout_width=\ "wrap_content\" \ n "+" android:layout_height=\ "wrap_content\" \ n "+" Style=\ "@android: style/widget.progressbar.small.inverse\"/>\n "+" <textview andRoid:id=\ "@+id/tv_loading\" \ n "+" android:layout_width=\ "wrap_content\" \ n "+" Android:layout_hei Ght=\ "wrap_content\" \ n "+" android:layout_torightof=\ "@+id/loading_pb\" \ n "+" android:text=\ "in Load ... \ "/>\n" + "</LinearLayout>";p rivate static string xmlpath = "Empty.xml";p rivate static string viewinject = "@v Iewinject (r.id.%s) \ n ";p rivate static string Findviewbyid ="%s = (%s)%sfindviewbyid (r.id.%s); \ n ";p rivate static string V Iewname = "Private%s%s;\n";p rivate static xmlpullparserfactory factory;private static Xmlpullparser parser;public Stati c void Main (string[] args) {try {factory = xmlpullparserfactory.newinstance ();p arser = Factory.newpullparser (); Parserxmlnormal (New Bytearrayinputstream (Xml.getbytes ()), NULL); System.out.println ("-==============================================================");p Arserxml (new Bytearrayinputstream (Xml.getbytes ())); System.out.println ("***********************************************************");p Arserxmlnormal (New FileInputStream (Xmlpath), null); System.out.println ("-==============================================================");p Arserxml (new FileInputStream (New File (Xmlpath)));} catch (Exception e) {e.printstacktrace (); System.out.println ("Wrong, the egg hurts ah, can not run through it at once?" ");}} /** * dependent on xutis IOC * * @param is * @throws xmlpullparserexception * @throws ioexception */private static void Parserxml (I Nputstream is) throws Xmlpullparserexception, IOException {parser.setinput (IS, "UTF-8");//set the input stream and indicate the encoding method StringBuffer SB = new StringBuffer (); int eventtype = Parser.geteventtype (); while (eventtype! = xmlpullparser.end_document) {EventType = P Arser.next (); if (EventType = = Xmlpullparser.start_tag) {for (int i = 0, count = Parser.getattributecount (); I < count; i++) {if (Parser.getattributename (i). Equals ("Android:id")) {String id = parser.getattributevalue (i). Replace ("@+id/", ""); Sb.append (String.Format (viewinject, id)); StringBuffer IDSB = new StringBuffer ();//capitalize the first letter of all _ if (ID. Contains ("_")) {string[] args = Id.split ("_"); for (String S:args) {idsb.append (Touppercasefirstone (s));}} else {IDSB.A Ppend (Touppercasefirstone (ID));} Idsb.insert (0, "M"); Sb.append (String.Format (ViewName, Parser.getname (), idsb.tostring ()));}}} if (EventType = = xmlpullparser.end_document) {System.out.println (sb.tostring ());}}} /** * Normal way to generate Findviewbyid * * @param is * @param valueName * @throws xmlpullparserexception * @throws IOException */privat e static void Parserxmlnormal (InputStream is, String valueName) throws Xmlpullparserexception, IOException { Parser.setinput (IS, "UTF-8"); Sets the input stream and indicates how to encode if (valueName = = null) {valueName = "";} if (!valuename.contains (".") && valuename.length () > 0) {valuename.replace (valueName, ValueName + ".");} arraylist<string> ids = new arraylist<string> (); arraylist<string> views = new arraylist<string> (), int eventtype = Parser.geteventtype (); while (eventtype! = xmlpullparser.end_document) {EventType = Parser.next (); if (EveNttype = = Xmlpullparser.start_tag) {for (int i = 0, count = Parser.getattributecount (); I < count; i++) {if (parser.get AttributeName (i). Equals ("Android:id")) {String id = parser.getattributevalue (i). Replace ("@+id/", "" ");  StringBuffer IDSB = new StringBuffer ();//capitalize the first letter of all _ if (Id.contains ("_")) {string[] args = Id.split ("_"); for (String s: args) {Idsb.append (Touppercasefirstone (s));}} else {idsb.append (Touppercasefirstone (ID));} Idsb.insert (0, "M"); Views.add (String.Format (ViewName, Parser.getname (), idsb.tostring ())); Ids.add (String.Format ( Findviewbyid, Idsb.tostring (), Parser.getname (), ValueName, id));}}} if (EventType = = xmlpullparser.end_document) {for (String s:views) {System.out.print (s);} for (String s:ids) {System.out.print (s);}}}} First letter to uppercase public static String Touppercasefirstone (String s) {if (Character.isuppercase (S.charat (0))) return s; Elsereturn (New StringBuilder ()). Append (Character.touppercase (S.charat (0))). Append (s.substring (1)). ToString ();}}



Console Output Template:

Private LinearLayout mempty;private ProgressBar mloadingpb;private TextView mtvloading;mempty = (linearlayout) Findviewbyid (r.id.empty); MLOADINGPB = (ProgressBar) Findviewbyid (R.ID.LOADING_PB); mtvloading = (TextView) Findviewbyid (r.id.tv_loading);-============================================================== @ViewInject ( R.id.empty) Private LinearLayout mempty, @ViewInject (R.ID.LOADING_PB) private ProgressBar MLOADINGPB; @ViewInject ( r.id.tv_loading) Private TextView mtvloading;***************************************************************** Private LinearLayout mempty;private ProgressBar mloadingpb;private TextView mtvloading;mempty = (linearlayout) Findviewbyid (r.id.empty); MLOADINGPB = (ProgressBar) Findviewbyid (R.ID.LOADING_PB); mtvloading = (TextView) Findviewbyid (r.id.tv_loading);-============================================================== @ViewInject ( R.id.empty) Private LinearLayout mempty, @ViewInject (R.ID.LOADING_PB) private ProgressBar MLOADINGPB; @ViewInject ( r.id.tv_loading) Private TexTView mtvloading; 



Here just to facilitate their own development, reduce labor, so the code is not well written, can be used. Friends who are interested can change their own. Finally, give the demo:http://www.oschina.net/code/snippet_924286_44839

The layout in Android turns into Java code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.