通过写一个简单的配置文件,自动扩展生成相应的代码,从而可以偷点小懒。
配置文件如下:
TextView:money
TextView:name
TextView:age
ImageView:headImg
ruby 代码生成器如下:
require 'erb'
class FindViewById
class << self
def get_type_ab(type)
case type
when "TextView"
"Tv"
when "ImageView"
"Iv"
when "GridView"
"Gv"
when "ListView"
"Lv"
when "Gallery"
"Gv"
end
end
def get_attrs_from(conf_file)
File.open(conf_file) do |f|
result = []
f.each_line do |line|
line = line.chomp
line = line.gsub(/\s+/,"")
type_name = line.split(":")
next if type_name.size != 2
name = nil
name = "m" << type_name[1].capitalize
ab = get_type_ab(type_name[0])
name << ab if ab != nil
attr = Attr.new(type_name[0], name)
attr.id = type_name[1]
result << attr
end
result
end
end
def out(conf_file)
erb = ERB.new(template(conf_file))
str = erb.result(binding)
end
def 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 %>
}
end
end
class Attr
def initialize(type,name)
@type,@name = type,name
end
def id=(id)
@id = id
end
attr_accessor :type, :name,:id
end
end
#---------------------------------------run code----------------------------
conf_file = "test.conf"
conf_file = ARGV[0] if ARGV.size > 0
generate_code = FindViewById.out(conf_file)
puts generate_code
生成的代码如下:
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" />
将这些代码copy到指定地方即可,简单吧?