Skip to content

Instantly share code, notes, and snippets.

@yareally
Last active August 29, 2015 14:08
Show Gist options
  • Save yareally/589855a3c5e4d73410b1 to your computer and use it in GitHub Desktop.
Save yareally/589855a3c5e4d73410b1 to your computer and use it in GitHub Desktop.
Scala features being used on Android
package com.example.android_scala
import android.app.Activity
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import android.widget.{Button, Toast}
import com.example.android_scala.MyActivity._
class MyActivity extends Activity {
/**
* Test random scala stuff and see if it works on Android
*/
override def onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
val btn = this.findView[Button](R.id.btn)
btn.click((view: View) ⇒
Toast.makeText(this,
"This toast was made by auto-implementing a View.OnClickListener " +
"through an implicit function and a lambda passed to setOnClickListener",
Toast.LENGTH_SHORT).show()
)
}
}
object MyActivity {
implicit class PimpMyView(val view: View) extends AnyVal {
def click(funct: (View) ⇒ Unit) = view.setOnClickListener(new OnClickListener {
override def onClick(v: View): Unit = funct(v)
})
}
implicit class PimpMyActivity(val a: Activity) extends AnyVal {
/**
* Generic Type method to deal with annoying conversions for views
*
* @param id - the Resource ID for the view in question
* @tparam T - the type associated with the widget (Button, TextView, etc)
* @return the found view with the desired type
*/
def findView[T](id: Int): T = {
a.findViewById(id).asInstanceOf[T]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment