创建一个FindView的trait
定义findView方法简化了findViewById(id).asInstanceOf
同时定义implicit简化了setOnClickListener
package org.noahx.scalaandroid
import android.app.Activity
import android.view.View
trait FindView extends Activity {
def findView[WidgetType](id: Int): WidgetType = {
findViewById(id).asInstanceOf[WidgetType]
}
}
class ViewWithOnClick(view: View) {
def onClick(action: View => Any) = {
view.setOnClickListener(new View.OnClickListener() {
def onClick(v: View) { action(v) }
})
}
}
object FindView extends Activity {
implicit def addOnClickToViews(view: View) =
new ViewWithOnClick(view)
}
有了以上的定义我们的原有的Activity就可以修改为
package org.noahx.scalaandroid
import android.app.Activity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.view.View
import FindView._
class ScalaAndroidActivity extends Activity with FindView {
lazy val text = findView[TextView](R.id.text1)
lazy val button = findView[Button](R.id.button1)
override protected def onCreate(savedInstanceState: Bundle) = {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
button.onClick { view: View =>
text.setText("hello scala!!!")
}
}
}
lazy方式也可以让组件定义全局化,便于使用
利用Scala语言的特点,代码变得简洁优雅