Turn writing code into a simple copy operation. One of the Code generators is --------- android, findViewById
By writing a simple configuration file, the code is automatically extended to generate the corresponding code, which can be 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 "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_name.size != 2name = nilname = "m" << type_name[1].capitalizeab = get_type_ab(type_name[0])name << ab if ab != nilattr = 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 |attr| %><%= 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);}
Just copy the code to the specified place. Is it easy?