Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 讓寫代碼變成簡單的copy操作,代碼生成器之一---------android,findViewById

讓寫代碼變成簡單的copy操作,代碼生成器之一---------android,findViewById

編輯:關於Android編程

通過寫一個簡單的配置文件,自動擴展生成相應的代碼,從而可以偷點小懶。

配置文件如下:


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);

}










將這些代碼copy到指定地方即可,簡單吧?

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved