Created
August 15, 2018 03:28
-
-
Save cong91/f7cd59f8fe34fba01864b564a01675c1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package com.example.congnt.baseproject; | |
| import android.arch.lifecycle.ViewModelProviders; | |
| import android.os.Bundle; | |
| import android.os.PersistableBundle; | |
| import android.support.annotation.Nullable; | |
| import android.support.v7.app.AppCompatActivity; | |
| import java.lang.reflect.ParameterizedType; | |
| public class BaseActivity<VM extends BaseViewModel> extends AppCompatActivity{ | |
| protected VM viewModel; | |
| @Override | |
| protected void onCreate(@Nullable Bundle savedInstanceState) { | |
| super.onCreate(savedInstanceState); | |
| Class<VM> clazz = getViewModelClass(); | |
| if(clazz == null) | |
| throw new IllegalArgumentException("You should add 'viewModel' variable"); | |
| viewModel = ViewModelProviders.of(this).get(clazz); | |
| } | |
| public Class<VM> getViewModelClass() { | |
| String name = ((ParameterizedType) getClass().getGenericSuperclass()) | |
| .getActualTypeArguments()[0].toString(); | |
| Class clazz = null; | |
| try { | |
| clazz = Class.forName(name.replace("class ", "")); | |
| } catch (ClassNotFoundException e) { | |
| e.printStackTrace(); | |
| } | |
| return clazz; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment