Skip to content

Instantly share code, notes, and snippets.

@cong91
Created August 15, 2018 03:28
Show Gist options
  • Select an option

  • Save cong91/f7cd59f8fe34fba01864b564a01675c1 to your computer and use it in GitHub Desktop.

Select an option

Save cong91/f7cd59f8fe34fba01864b564a01675c1 to your computer and use it in GitHub Desktop.
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