Android implements the initialization code method for automatically generating layout View

  • 2020-06-12 10:33:57
  • OfStack

Interface layout is extremely important in android development, but it is also complex. Sometimes we rush to actually run the layout to see what it looks like. But I don't want to make fun of android's compilation speed, especially as layouts get more complex, projects get bigger, and resource files get bigger.

In particular, it is the initialization of view for android. findViewbyId is completely manual work, and we can automatically generate the initialization code of View according to the layout file.

First of all, let me state:

1. It's extremely easy to do, just as practical, but extremely useful in complex layouts and when you first write the initial View code.
2. Only view initialization code with id tag can be generated.

Train of thought

It's as simple as parsing the layout layout file, storing some information (tag type, id name, etc.) about the tags that have id attributes, and then generating fixed code based on that information.

implementation

The first step is to parse the layout file and put the parsed information into one list


public class SaxHander extends DefaultHandler {
    private List<IdNamePair> map = new ArrayList<IdNamePair>();
 
    
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        map.clear();
    }
 
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
//      System.out.println("-------------------------------------");
 
        String tempid = attributes.getValue("id");
        String id = null;
        if (tempid != null) {
            String[] ss = tempid.split("/");
            if (ss != null && ss.length == 2) {
 
                id = ss[1];
            }
        }
        if (id != null) {
            map.add(new IdNamePair(id, qName));
 
        }
//      System.out.println(id);
//      System.out.println(qName);
 
    }
 
    public List<IdNamePair> getRes() {
        return map;
 
    }
}


public class IdNamePair {
    private String  id;
    private String name;
    
    /**
     * @param id
     * @param name
     */
    public IdNamePair(String id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

And then 1 bit of splicing code


 public class ViewCodeUtil {
    static SAXParserFactory saxfac = SAXParserFactory.newInstance(); 
 
    static SaxHander mySax = new SaxHander();
 
    
    public static String getCode(String resFileName){
        
        File f = new File(resFileName);
        if (!f.exists()) {
            return null;
        }
        
        try {
            saxfac.newSAXParser().parse(f,mySax);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        
        List<IdNamePair> res = mySax.getRes();
        StringBuilder sb = new StringBuilder();
        StringBuilder sb1 = new StringBuilder();
        sb.append("//---------- Let's start defining the domain --------------\n");
        
        sb1.append("//---------- start initView methods ------------------\n");
        sb1.append("public void initView() { \n");
 
        for (IdNamePair idNamePair : res) {
            sb.append(" private "+idNamePair.getName()+"  "+ idNamePair.getId()+idNamePair.getName()+";\n");
            
            sb1.append("    "+idNamePair.getId()+idNamePair.getName()+" = ("+idNamePair.getName()+")findViewById(R.id."+idNamePair.getId()+");\n");
        
        }
        sb1.append("}\n");
//      System.out.println(sb.toString());
//      System.out.println(sb1.toString());
        return sb.append(sb1.toString()).toString();
 
    }

Finally, test the class main method.


public class Test {
    
    private static final String[] layoutFiles ={"./res/g_ruler.xml","./res/report.xml"};
    
    public static void main(String[] args) {
        
        
        if (args!=null) {
            for (int i = 0; i < args.length; i++) {
                System.out.println("");
 
                System.out.println("---------"+args[i]+"----------");
                System.out.println(ViewCodeUtil.getCode(args[i]));
            } 
        }
        
        for (int i = 0; i < layoutFiles.length; i++) {
            System.out.println("");
 
            System.out.println("//---------"+layoutFiles[i]+"----------");
            System.out.println(ViewCodeUtil.getCode(layoutFiles[i]));
        } 
        
    }
 
}


Related articles: