DataBinderWriter.kt revision fead9ca09b117136b35bc5bf137340a754f9eddd
1/* 2 * Copyright (C) 2015 The Android Open Source Project 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * http://www.apache.org/licenses/LICENSE-2.0 7 * Unless required by applicable law or agreed to in writing, software 8 * distributed under the License is distributed on an "AS IS" BASIS, 9 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 * See the License for the specific language governing permissions and 11 * limitations under the License. 12 */ 13 14package android.databinding.tool.writer 15 16import android.databinding.tool.LayoutBinder 17 18class DataBinderWriter(val pkg: String, val projectPackage: String, val className: String, val layoutBinders : List<LayoutBinder> ) { 19 fun write() = 20 kcode("") { 21 nl("package $pkg;") 22 nl("import $projectPackage.BR;") 23 nl("class $className implements android.databinding.DataBinderMapper {") { 24 tab("@Override") 25 tab("public android.databinding.ViewDataBinding getDataBinder(android.view.View view, int layoutId) {") { 26 tab("switch(layoutId) {") { 27 layoutBinders.groupBy{it.getLayoutname()}.forEach { 28 tab("case ${it.value.first!!.getModulePackage()}.R.layout.${it.value.first!!.getLayoutname()}:") { 29 if (it.value.size() == 1) { 30 tab("return new ${it.value.first!!.getPackage()}.${it.value.first!!.getClassName()}(view);") 31 } else { 32 // we should check the tag to decide which layout we need to inflate 33 tab("{") { 34 tab("final String tag = (String)view.getTag();") 35 tab("if(tag == null) throw new java.lang.RuntimeException(\"view must have a tag\");") 36 it.value.forEach { 37 // TODO don't use strings. not necessary 38 tab("if (tag.equals(String.valueOf(${it.getId()}))) {") { 39 tab("return new ${it.getPackage()}.${it.getClassName()}(view);") 40 } tab("}") 41 } 42 }tab("}") 43 } 44 45 } 46 } 47 } 48 tab("}") 49 tab("return null;") 50 } 51 tab("}") 52 53 tab("public int getId(String key) {") { 54 tab("return BR.getId(key);") 55 } tab("}") 56 } 57 nl("}") 58 }.generate() 59}