Java 类android.arch.lifecycle.ViewModelProviders 实例源码

项目:GSoC-Info-Android    文件:MainPageFragment.java   
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_about, container, false);
    RecyclerView recyclerView = view.findViewById(R.id.rv_timeline);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    MainPageViewModel mainPageViewModel = ViewModelProviders.of(getActivity()).get(MainPageViewModel.class);
    timelineAdapter = new TimelineAdapter();
    recyclerView.setAdapter(timelineAdapter);
    mainPageViewModel.getMainPageCopy().observe(this, new Observer<MainPage.Copy>() {
        @Override
        public void onChanged(@Nullable MainPage.Copy copy) {
            timelineAdapter.setData(copy);
        }
    });
    return view;
}
项目:file.io-app    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    /* Animate the views */
    MaterialIn.animate(rootView);

    /* Get the view model */
    uploadItemViewModel = ViewModelProviders.of(this).get(UploadItemViewModel.class);

    /* Handle incoming intent content */
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    // FIXME: Google photos URI
    if (type != null) {
        Log.d(TAG, "Receive Type: " + type);
        Uri fileUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
        Log.d(TAG, "\nURI: " + fileUri);
        if (Intent.ACTION_SEND.equals(action) && fileUri != null) {
            handleExplicitFileShare(intent);
        }
    }
    linkTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Copy the content of the link text to Clipboard
            ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("link", linkTextView.getText());
            if (clipboardManager != null) {
                clipboardManager.setPrimaryClip(clipData);
                Toast.makeText(MainActivity.this, getString(R.string.link_copy), Toast.LENGTH_SHORT).show();
            }
        }
    });
}
项目:android-arch-mvvm    文件:LoginActivity.java   
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_activity_layout);

    // step0 获取相关的viewModel
    mLoginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);

    // step1 获取view
    mLoginBtn = (Button) findViewById(R.id.loginBtn);

    // step2 设置监听
    mLoginBtn.setOnClickListener(this);

    // setp3 绑定数据
    mLoginViewModel.loginResult.observe(this, mLoginObserver);
}
项目:MVVMArms    文件:WeatherDailyFragment.java   
@Override
public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //获取 Activity 的ViewModel 来共享数据
    mWeatherViewModel = ViewModelProviders.of(getActivity(), mViewModelFactory).get(WeatherViewModel.class);
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(WeatherDailyViewModel.class);
    mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_weather_daily, container, false);
    //设置ViewModel
    mBinding.setViewModel(mViewModel);
    mBinding.retry.setViewModel(mViewModel);
    mBinding.retry.setRetry(mViewModel);
    mBinding.weatherSource.setViewModel(mViewModel);
    //RecyclerView设置Adapter
    mBinding.recyclerWeatherDaily.setAdapter(mAdapter);
    //设置Refresh
    mBinding.refresh.setColorSchemeColors(
            ContextCompat.getColor(getContext(), R.color.colorPrimary),
            ContextCompat.getColor(getContext(), R.color.colorAccent),
            ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
    return mBinding.getRoot();
}
项目:friendlyeats-android    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(mToolbar);

    // View model
    mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);

    // Enable Firestore logging
    FirebaseFirestore.setLoggingEnabled(true);

    // Initialize Firestore and the main RecyclerView
    initFirestore();
    initRecyclerView();

    // Filter Dialog
    mFilterDialog = new FilterDialogFragment();
}
项目:MVP-Architecture-Components    文件:BaseActivity.java   
@SuppressWarnings("unchecked")
@CallSuper
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    BaseViewModel<V, P> viewModel = ViewModelProviders.of(this).get(BaseViewModel.class);
    boolean isPresenterCreated = false;
    if (viewModel.getPresenter() == null) {
        viewModel.setPresenter(initPresenter());
        isPresenterCreated = true;
    }
    presenter = viewModel.getPresenter();
    presenter.attachLifecycle(getLifecycle());
    presenter.attachView((V) this);
    if (isPresenterCreated)
        presenter.onPresenterCreated();
}
项目:MVP-Architecture-Components    文件:BaseFragment.java   
@SuppressWarnings("unchecked")
@CallSuper
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    BaseViewModel<V, P> viewModel = ViewModelProviders.of(this).get(BaseViewModel.class);
    boolean isPresenterCreated = false;
    if (viewModel.getPresenter() == null) {
        viewModel.setPresenter(initPresenter());
        isPresenterCreated = true;
    }
    presenter = viewModel.getPresenter();
    presenter.attachLifecycle(getLifecycle());
    presenter.attachView((V) this);
    if (isPresenterCreated)
        presenter.onPresenterCreated();
}
项目:recyclerview-android    文件:MultipleChoiceModeExampleActivity.java   
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_multiple_choice_mode_example);

    final PersonsViewModel viewModel = ViewModelProviders.of(this).get(PersonsViewModel.class);
    final Datasource<Person> datasource = viewModel.getDatasource();
    final CheckedPersonsAdapter adapter = new CheckedPersonsAdapter(datasource, true);

    mRecyclerView = (RecyclerView) findViewById(android.R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setAdapter(adapter);

    mChoiceMode = new MultipleChoiceMode(savedInstanceState);
    mChoiceMode.setChoiceModeListener(this::onItemCheckedChanged);
    mChoiceModeHelper = new ChoiceModeHelper<>(adapter, mChoiceMode);
    mChoiceModeHelper.setRecyclerView(mRecyclerView);

    findViewById(R.id.action_clear_choices).setOnClickListener(v -> mChoiceMode.clearChoices());
    findViewById(R.id.action_get_checked_items).setOnClickListener(v -> showCheckedItems());
}
项目:app-android    文件:VmTestActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_vm_test);
    ButterKnife.bind(this);

    testViewModel = ViewModelProviders.of(this).get(TestViewModel.class);
    testViewModel.getMutableIntList().observe(this, list -> {
        Timber.d("trigger %s", list);
        if (list != null) {
            textNumList.setText(list.toString());
        }
    });

    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null)
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}
项目:recyclerview-android    文件:SingleModalChoiceModeExampleActivity.java   
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_single_modal_choice_mode_example);

    mViewModel = ViewModelProviders.of(this).get(PersonsViewModel.class);
    final Datasource<Person> datasource = mViewModel.getDatasource();
    final ActivatedPersonsAdapter adapter = new ActivatedPersonsAdapter(datasource);

    mRecyclerView = (RecyclerView) findViewById(android.R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setAdapter(adapter);

    final ActionModeCompat actionMode = ActionModeCompat.from(this);
    mChoiceMode = new SingleModalChoiceMode(actionMode, mModalChoiceModeListener, savedInstanceState);
    // mChoiceMode.setStartOnSingleTapEnabled(true);
    // mChoiceMode.setFinishActionModeOnClearEnabled(false);

    mChoiceModeHelper = new ChoiceModeHelper<>(adapter, mChoiceMode);
    mChoiceModeHelper.setOnItemClickListener(this::onItemClick);
    mChoiceModeHelper.setRecyclerView(mRecyclerView);

    findViewById(R.id.action_clear_choices).setOnClickListener(v -> mChoiceMode.clearChoices());
    findViewById(R.id.action_get_checked_item).setOnClickListener(v -> showCheckedItem());
}
项目:android-instant-apps-demo    文件:CartActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);
    viewModel = ViewModelProviders.of(this).get(CartViewModel.class);

    fab = (FloatingActionButton) findViewById(R.id.fab);
    toolbar = (Toolbar) findViewById(R.id.toolbar);

    setupToolbar();
    handleDeepLink();

    fab.setImageDrawable(VectorDrawableCompat.create(getResources(), R.drawable.ic_share_white_24dp, null));
    fab.setOnClickListener(view -> {
        String cartId = viewModel.getCartId().getValue();
        ShareCompat.IntentBuilder.from(this)
                .setText(String.format(Locale.US, "Check out my shopping cart now using Android Instant Apps! \n%s/cart/%s", ROOT_ENDPOINT, cartId))
                .setType("text/plain")
                .setChooserTitle(share_cart)
                .startChooser();
    });
}
项目:EasyIPC    文件:EasyIpcArchActivity.java   
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
    recyclerView.setAdapter(adapter = new Adapter());

    viewModel = ViewModelProviders
            .of(this)
            .get(IpcViewModel.class)
            .init(MainService.class, BIND_AUTO_CREATE);

    viewModel.dispatchEvent(new EarlyData("sent from the activity")); // get's queued

    viewModel
            .getLiveData(Data.class)
            .observe(ProcessLifecycleOwner.get(), onData);

    viewModel
            .getLiveData(Data.List.class)
            .observe(this, onDataList);

    viewModel
            .getLiveData(EarlyData.class)
            .observe(this, onEarlyData);

}
项目:RoomDemo2017    文件:ListFragment.java   
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    //Set up and subscribe (observe) to the ViewModel
    listItemCollectionViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(ListItemCollectionViewModel.class);

    listItemCollectionViewModel.getListItems().observe(this, new Observer<List<ListItem>>() {
        @Override
        public void onChanged(@Nullable List<ListItem> listItems) {
            if (ListFragment.this.listOfData == null) {
                setListData(listItems);
            }
        }
    });

}
项目:RoomDemo2017    文件:DetailFragment.java   
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    //Set up and subscribe (observe) to the ViewModel
    listItemViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(ListItemViewModel.class);

    listItemViewModel.getListItemById(itemId).observe(this, new Observer<ListItem>() {
        @Override
        public void onChanged(@Nullable ListItem listItem) {
            if (listItem != null) {
                dateAndTime.setText(listItem.getItemId());
                message.setText(listItem.getMessage());
                coloredBackground.setImageResource(listItem.getColorResource());
            }

        }
    });


}
项目:android-architecture-components    文件:UserFragment.java   
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    userViewModel = ViewModelProviders.of(this, viewModelFactory).get(UserViewModel.class);
    userViewModel.setLogin(getArguments().getString(LOGIN_KEY));
    userViewModel.getUser().observe(this, userResource -> {
        binding.get().setUser(userResource == null ? null : userResource.data);
        binding.get().setUserResource(userResource);
        // this is only necessary because espresso cannot read data binding callbacks.
        binding.get().executePendingBindings();
    });
    RepoListAdapter rvAdapter = new RepoListAdapter(dataBindingComponent, false,
            repo -> navigationController.navigateToRepo(repo.owner.login, repo.name));
    binding.get().repoList.setAdapter(rvAdapter);
    this.adapter = new AutoClearedValue<>(this, rvAdapter);
    initRepoList();
}
项目:app-android    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    //UI elements setup
    setSupportActionBar(toolbar);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    navigationView.setNavigationItemSelectedListener(this);


    //Init shared usermodels
    ViewModelProviders.of(this).get(SharedUserViewModel.class);


    //Init nav, Load dashboard fragment
    NavigationController.init(this);
    NavigationController.getInstance().navigateToDashboard();
}
项目:Android-CleanArchitecture-Java    文件:WikiEntryActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //WikiEntry feature component scope start here
    ((CleanArchApp)getApplication()).buildWikiEntryComponent();

    setContentView(R.layout.activity_main);

    title = (EditText) findViewById(R.id.entryTitle);
    TextView extract = (TextView) findViewById(R.id.entryDetails);
    Button submitButton = (Button) findViewById(R.id.submitButton);
    submitButton.setOnClickListener(submitButtonOnClickListener);

    progressBar = (ContentLoadingProgressBar) findViewById(R.id.progressBar);

    wikiEntryViewModel = ViewModelProviders.of(this).get(WikiEntryViewModel.class);
    wikiEntryViewModel.getWikiEntry().observe(this, wikiEntry -> {

        Log.d(TAG, "received update for wikiEntry");
        extract.setText(wikiEntry.getExtract());
        progressBar.hide();
    });
}
项目:mvvm-template    文件:ContributorsFragment.java   
@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        adapter.setContributor(true);
        adapter.setFilter(false);
        recyclerView.addKeyLineDivider();
        RepoDetailViewModel repoDetailViewModel = ViewModelProviders.of(getActivity()).get(RepoDetailViewModel.class);
        repoDetailViewModel.getOnDataReady().observe(this, ready -> {
            if (ready != null && ready) {
                // noinspection ConstantConditions
                viewModel.initRepoDetail(repoDetailViewModel);
            }
        });
        setNoDataText("No Contributors");
        viewModel.getContributorsCount().observe(this, count -> {
            int n = count != null ? count : 0;
            Fragment fragment = getParentFragment();
            if (fragment != null && fragment instanceof TabBadgeListener) {
//                ((TabBadgeListener) fragment).setBadge(1, n);
            }
        });
    }
项目:mapbox-navigation-android    文件:NavigationView.java   
private void initViewModels() {
  try {
    locationViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(LocationViewModel.class);
    routeViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(RouteViewModel.class);
    navigationViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(NavigationViewModel.class);
  } catch (ClassCastException exception) {
    throw new ClassCastException("Please ensure that the provided Context is a valid FragmentActivity");
  }
}
项目:SampleAppArch    文件:FeedActivityModule.java   
/**
 * Created by Charles Ng on 26/9/2017.
 */


@Provides
FeedEntryListViewModel provideViewModel(FeedEntry feedEntry, FeedActivity feedActivity,
    FeedEntryListViewModelFactory factory) {
  FeedEntryListViewModel viewModel = ViewModelProviders.of(feedActivity, factory)
      .get(FeedEntryListViewModel.class);
  viewModel.getFeedEntry().set(feedEntry);
  return viewModel;
}
项目:SampleAppArch    文件:SimpleListActivityModule.java   
@Provides
SimpleMasterDetailShareViewModel provideVm(SimpleListActivity simpleListActivity,
    SimpleMasterDetailShareViewModelFactory factory) {
  return ViewModelProviders
      .of(simpleListActivity, factory).get(SimpleMasterDetailShareViewModel.class);

}
项目:ArchitectureComponents    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewModel = ViewModelProviders.of(this).get(FilmsViewModel.class);
    viewModel.init();
    lstFIlms = (ListView) findViewById(R.id.lstFilms);

    subscribeUi(viewModel);

    getLifecycle().addObserver(this);
}
项目:DataBindingDemos    文件:CounterActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    CounterViewModel viewModel = ViewModelProviders.of(this).get(CounterViewModel.class);

    ActivityCounterBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_counter);
    binding.setViewModel(viewModel);
}
项目:PADC-MyanmarAttractions-AC    文件:AttractionListActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attraction_list);
    ButterKnife.bind(this, this);

    setActionBar(toolbar);

    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setTitle(getString(R.string.app_title_mm));
    }

    mAttractionAdapter = new AttractionAdapter(getApplicationContext(), this);
    rvAttractions.setAdapter(mAttractionAdapter);

    LinearLayoutManager verticalSingleColumnLM = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
    rvAttractions.setLayoutManager(verticalSingleColumnLM);

    mAttractionsModel = ViewModelProviders.of(this).get(AttractionsModel.class);
    mAttractionsModel.initDatabase(getApplicationContext());
    mAttractionsModel.getAttractions().observe(this, new Observer<List<AttractionVO>>() {
        @Override
        public void onChanged(@Nullable List<AttractionVO> attractionVOs) {
            mAttractionAdapter.setNewData(attractionVOs);
        }
    });
}
项目:RxRedux    文件:UserListActivity.java   
@Override
public void initialize() {
    eventObservable = Observable.empty();
    viewModel = ViewModelProviders.of(this,
            new ViewModelFactory(DataServiceFactory.getInstance())).get(UserListVM.class);
    if (viewState == null) {
        eventObservable = Single.<BaseEvent>just(new GetPaginatedUsersEvent(0))
                .doOnSuccess(event -> Log.d("GetPaginatedUsersEvent", FIRED)).toObservable();
    }
}
项目:MVVMArms    文件:WeatherActivity.java   
@Override
public int initView(Bundle savedInstanceState) {
    //创建ViewModel
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(WeatherViewModel.class);
    if (savedInstanceState != null) {
        //Restore data
        mReplace = savedInstanceState.getInt(EventBusTags.ACTIVITY_FRAGMENT_REPLACE);
    }
    return R.layout.activity_weather;
}
项目:Android-ArchComponents    文件:MainActivity.java   
private void callLocationListener() {
    ViewModelProviders.of(this)
            .get(MainActivityViewModel.class)
            .getLocation(this)
            .observe(this, location -> {
                // Update UI
            });
}
项目:Android-Code-Demos    文件:LoginActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ViewModelFactory factory = ViewModelFactory.getInstance(getApplication());
    final LoginViewModel loginViewModel =
            ViewModelProviders.of(this, factory).get(LoginViewModel.class);

    final ActivityLoginBinding binding =
            DataBindingUtil.setContentView(this, R.layout.activity_login);
    binding.setViewmodel(loginViewModel);

    loginViewModel.getOpenUserList().observe(this, new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            Intent intent = new Intent(LoginActivity.this, UserListActivity.class);
            intent.putExtra("token", s);
            startActivity(intent);
            finish();
        }
    });

    loginViewModel.getSnackbarMessage().observe(this, new SnackbarMessage.SnackbarObserver() {
        @Override
        public void onNewMessage(String message) {
            SnackbarUtil.showSnackbar(binding.getRoot(), message);
        }
    });

    findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loginViewModel.login();
        }
    });
}
项目:FitnessHabits    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
    viewModel.init(FitnessHabitsApplication.application.getParamRepository());
}
项目:permission-bitte    文件:ArchitectureComponentsActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    findViewById(R.id.button).setOnClickListener(this);
    vm = ViewModelProviders.of(this).get(ArchitectureComponentsViewModel.class);
    vm.getState().observe(this, this);
    vm.shouldAskPermission(PermissionBitte.shouldAsk(this, vm));

}
项目:DaggerAndroidMVVM    文件:LobbyActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    AndroidInjection.inject(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lobby_activity);

    ButterKnife.bind(this);

    viewModel = ViewModelProviders.of(this, viewModelFactory).get(LobbyViewModel.class);

    viewModel.response().observe(this, response -> processResponse(response));
}
项目:Moneycim    文件:AddAndEditSpendingFragment.java   
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    viewModel = ViewModelProviders.of(this).get(AddAndEditSpendingViewModel.class);
    subscribeSpendingGroups();
    if(spendingGroupList != null){
        fillSpinner(groupSpinner, spendingGroupList);
    }
}
项目:LabDayApp    文件:LoginFragment.java   
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(LoginViewModel.class);

    observeLogin();
}
项目:GmArchMvvm    文件:RtoFragment.java   
@Override
public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(RtoViewModel.class);
    mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_rto, container, false);
    mBinding.setViewModel(mViewModel);//Set ViewModel
    return mBinding.getRoot();
}
项目:android-persistence    文件:BooksBorrowedByUserActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.db_activity);
    mBooksTextView = findViewById(R.id.books_tv);

    // Get a reference to the ViewModel for this screen.
    mViewModel = ViewModelProviders.of(this).get(BooksBorrowedByUserViewModel.class);

    // Update the UI whenever there's a change in the ViewModel's data.
    subscribeUiBooks();
}
项目:android-persistence    文件:TypeConvertersActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.db_activity);
    mBooksTextView = findViewById(R.id.books_tv);

    // Get a reference to the ViewModel for this screen.
    mViewModel = ViewModelProviders.of(this).get(TypeConvertersViewModel.class);

    // Update the UI whenever there's a change in the ViewModel's data.
    subscribeUiBooks();
}
项目:Inshorts    文件:ArticleListActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_article_list);

    ButterKnife.bind(this);

    mRootView = findViewById(R.id.root);

    //Getting the ApiService
    ApiService apiService = NetworkInstance.getInstance(this).getApiService();

    //Getting the Database
    AppDatabase database = Room.databaseBuilder(getApplicationContext(),
            AppDatabase.class, AppDatabase.DB_NAME).build();

    //Getting the ViewModel
    ListActivityViewModel.Factory factory = new ListActivityViewModel.Factory(getApplication(),
            new RepositoryImpl(apiService, database));
    mViewModel = ViewModelProviders.of(this, factory).get(ListActivityViewModel.class);

    rvArticleList.setLayoutManager(new LinearLayoutManager(this));

    NetworkInfo.getInstance(this).observe(this, connectedToInternet -> {
        if (!connectedToInternet) {
            //offline
            showMsg(getString(R.string.no_internet));
        } else {
            //online fetch the list if not fetched already
            mViewModel.fetchListIfNotFetched();
        }
    });
}
项目:android-persistence    文件:BooksBorrowedByUserActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.db_activity);
    mBooksTextView = findViewById(R.id.books_tv);

    // Get a reference to the ViewModel for this screen.
    mViewModel = ViewModelProviders.of(this).get(BooksBorrowedByUserViewModel.class);

    // Update the UI whenever there's a change in the ViewModel's data.
    subscribeUiBooks();
}
项目:lead-management-android    文件:ContactsFragment.java   
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_contacts, container, false);
    setHasOptionsMenu(true);
    mUnbinder = ButterKnife.bind(this, view);

    mViewModel = ViewModelProviders.of(this).get(ContactsFragmentViewModel.class);
    mViewModel.getContacts().observe(this, contacts -> {
        mAdapter.replaceData(contacts);
    });

    final MainActivity activity = (MainActivity) getActivity();
    if (activity != null) {
        activity.initFab();
    }

    mAdapter = new ContactsAdapter(this);
    recyclerView.setAdapter(mAdapter);

    textView.setVisibility(View.GONE);

    swipeToRefresh.setOnRefreshListener(() -> {
        mAdapter.replaceData(mViewModel.getContacts().getValue());
        swipeToRefresh.setRefreshing(false);
    });
    return view;
}
项目:recyclerview-android    文件:ListDatasourceExampleActivity.java   
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_datasource_example);

    mViewModel = ViewModelProviders.of(this).get(ListDatasourceExampleViewModel.class);

    final Datasource<Person> datasource = mViewModel.getDatasource();
    final PersonsAdapter adapter = new PersonsAdapter(datasource);

    mRecyclerView = (RecyclerView) findViewById(android.R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setAdapter(adapter);

    // Add click support to RecyclerView. Adapter implements ItemClickHelper.Callback
    mItemClickHelper = new ItemClickHelper<>(adapter);
    mItemClickHelper.setOnItemClickListener(this::onItemClick);
    mItemClickHelper.setOnItemLongClickListener(this::onItemLongClick);
    mItemClickHelper.setRecyclerView(mRecyclerView);

    // Add enable view holder behavior. Adapter implements SimpleEnableBehavior.Callback
    mViewHolderTracker = new ViewHolderTracker();
    mViewHolderTracker.registerViewHolderObserver(new RecursiveEnableBehavior(adapter));
    mViewHolderTracker.setRecyclerView(mRecyclerView);

    findViewById(R.id.action_add_item).setOnClickListener(v -> mViewModel.addSingleItem());
    findViewById(R.id.action_add_multiple_items).setOnClickListener(v -> mViewModel.addMultipleItems());
}