Last active
February 22, 2018 14:14
-
-
Save juliendn/f35f2646c70481ad1de2cb35652e0600 to your computer and use it in GitHub Desktop.
VM kotlin integration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ChronoActivity2 : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
// The ViewModelStore provides a new ViewModel or one previously created. | |
val chronometerViewModel = getViewModel(this) { | |
ChronometerViewModel(SystemClock.elapsedRealtime()) | |
} | |
// Get the chronometer reference | |
val chronometer = findViewById<Chronometer>(R.id.chronometer) | |
chronometer.base = chronometerViewModel.startTime | |
chronometer.start() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ChronometerViewModel(val startTime: Long) : ViewModel() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewModelFactory<VM : ViewModel>(private val creation: () -> VM) : ViewModelProvider.Factory { | |
@Suppress("UNCHECKED_CAST") | |
override fun <T : ViewModel> create(modelClass: Class<T>): T = creation() as T | |
} | |
inline fun <reified VM : ViewModel> getViewModel(activity: FragmentActivity, key: String? = null, noinline creation: () -> VM): VM { | |
return ViewModelProviders | |
.of(activity, ViewModelFactory(creation)) | |
.run { | |
if (null == key) { | |
get(VM::class.java) | |
} else { | |
get(key, VM::class.java) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment