1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package androidx.lifecycle.viewmodeltest; 18 19 import android.os.Bundle; 20 21 import androidx.annotation.Nullable; 22 import androidx.fragment.app.Fragment; 23 import androidx.fragment.app.FragmentActivity; 24 import androidx.lifecycle.ViewModelProviders; 25 import androidx.lifecycle.extensions.test.R; 26 27 public class ViewModelActivity extends FragmentActivity { 28 public static final String KEY_FRAGMENT_MODEL = "fragment-model"; 29 public static final String KEY_ACTIVITY_MODEL = "activity-model"; 30 public static final String FRAGMENT_TAG_1 = "f1"; 31 public static final String FRAGMENT_TAG_2 = "f2"; 32 33 public TestViewModel activityModel; 34 public TestViewModel defaultActivityModel; 35 36 @Override onCreate(@ullable Bundle savedInstanceState)37 protected void onCreate(@Nullable Bundle savedInstanceState) { 38 super.onCreate(savedInstanceState); 39 setContentView(R.layout.activity_view_model); 40 if (savedInstanceState == null) { 41 getSupportFragmentManager().beginTransaction() 42 .add(R.id.fragment_container, new ViewModelFragment(), FRAGMENT_TAG_1) 43 .add(new ViewModelFragment(), FRAGMENT_TAG_2) 44 .commit(); 45 } 46 activityModel = ViewModelProviders.of(this).get(KEY_ACTIVITY_MODEL, TestViewModel.class); 47 defaultActivityModel = ViewModelProviders.of(this).get(TestViewModel.class); 48 } 49 50 public static class ViewModelFragment extends Fragment { 51 public TestViewModel fragmentModel; 52 public TestViewModel activityModel; 53 public TestViewModel defaultActivityModel; 54 55 @Override onCreate(@ullable Bundle savedInstanceState)56 public void onCreate(@Nullable Bundle savedInstanceState) { 57 super.onCreate(savedInstanceState); 58 fragmentModel = ViewModelProviders.of(this).get(KEY_FRAGMENT_MODEL, 59 TestViewModel.class); 60 activityModel = ViewModelProviders.of(getActivity()).get(KEY_ACTIVITY_MODEL, 61 TestViewModel.class); 62 defaultActivityModel = ViewModelProviders.of(getActivity()).get(TestViewModel.class); 63 } 64 } 65 } 66