By writing a simple configuration file, automatic extension generates the corresponding code, so that you can steal a little lazy.
The configuration file is as follows:
TextView:moneyTextView:nameTextView:ageImageView:headImg
The Ruby code generator is as follows:
Require ' Erb ' class Findviewbyidclass << selfdef get_type_ab (type) case Typewhen "TextView" "Tv" when "ImageView" "Iv "When" the GridView "GV" when "ListView" "Lv" when "Gallery" "GV" Endenddef Get_attrs_from (conf_file) File.Open (conf_file) do |f|result = [] f.each_line do |line|line = Line.chompline = Line.gsub (/\s+/, "") Type_name = Line.split (":") Next if Type_nam E.size! = 2name = Nilname = "M" << Type_name[1].capitalizeab = Get_type_ab (type_name[0]) name << AB if ab! = NI Lattr = Attr.new (type_name[0], name) Attr.id = Type_name[1]result << attrendresultendenddef out (conf_file) Erb = Erb . New (Template (conf_file)) str = Erb.result (binding) enddef template (conf_file) template =%{<% Attrs = Findviewbyid.get_attrs_from (conf_file)%><% Attrs.each do |attr| %>private <%= attr.type%> <%= attr.name%>;<% end%>private void Initviews () {<% Attrs.each do |a ttr| %><%= attr.name%> = (<%= attr.type%>) Findviewbyid (r.id.<%= attr.id%>); <% End%>}<% Attrs.each do |attr| %><<%= attr.type%> android:layout_width= "wrap_content" android_layout_height= "Wrap_content" Android:id = "@+id/<%= attr.id%>"/><% End%>}endendclass Attrdef Initialize (type,name) @type, @name = Type, Nameenddef id= (id) @id = idendattr_accessor:type,: name,:idendend#---------------------------------------Run Code----------------------------conf_file = "test.conf" Conf_file = argv[0] if argv.size > 0generate_code = Findviewbyid.out (conf_file) puts Generate_code
The generated code is as follows:
Private TextView mmoneytv;private TextView mnametv;private TextView magetv;private ImageView mheadimgiv;private void Initviews () {Mmoneytv = (TextView) Findviewbyid (R.id.money); Mnametv = (TextView) Findviewbyid (r.id.name); Magetv = ( TextView) Findviewbyid (r.id.age); mheadimgiv = (ImageView) Findviewbyid (r.id.headimg);} <textview android:layout_width= "wrap_content" android_layout_height= "wrap_content" android:id= "@+id/money"/ ><textview android:layout_width= "wrap_content" android_layout_height= "wrap_content" android:id= "@+id/name"/ ><textview android:layout_width= "wrap_content" android_layout_height= "wrap_content" android:id= "@+id/age"/ ><imageview android:layout_width= "wrap_content" android_layout_height= "wrap_content" android:id= "@+id/ Headimg "/>
Can you copy the code to the specified place?
Let the write code become a simple copy operation, one of the code generators---------Android,findviewbyid