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 17package android.databinding.testapp; 18 19import android.databinding.DataBindingUtil; 20import android.databinding.ViewDataBinding; 21import android.support.test.InstrumentationRegistry; 22import android.support.test.rule.ActivityTestRule; 23 24/** 25 * Convenience rule for tests that use data binding. 26 * @param <T> The type of the generated binding class 27 */ 28public class DataBindingTestRule<T extends ViewDataBinding> 29 extends ActivityTestRule<TestActivity> { 30 final int mLayoutId; 31 private T mBinding; 32 public DataBindingTestRule(int layoutId) { 33 super(TestActivity.class); 34 mLayoutId = layoutId; 35 } 36 37 @Override 38 protected void afterActivityLaunched() { 39 super.afterActivityLaunched(); 40 InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { 41 @Override 42 public void run() { 43 mBinding = DataBindingUtil.setContentView(getActivity(), mLayoutId); 44 } 45 }); 46 } 47 48 public T getBinding() { 49 return mBinding; 50 } 51 52 public void executePending() { 53 try { 54 runOnUiThread(new Runnable() { 55 @Override 56 public void run() { 57 mBinding.executePendingBindings(); 58 } 59 }); 60 } catch (Throwable throwable) { 61 throw new RuntimeException("unexpected problem in execute pending", throwable); 62 } 63 } 64} 65