我正在尝试测试新创建的活动(在方向更改后)是否正确重新初始化。下面的代码显示从 getActivity() 返回的活动是在 setUp() 中构造的活动,而不是新创建的活动。
测试:
public class MyActivityTest extends ActivityInstrumentationTestCase2<MyActivity>{
private static final String TAG = "RAMPS";
private MyActivity mActivity;
public MyActivityTest() {
super("com.ramps", MyActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
mActivity = getActivity();
Log.v(TAG, "setUp; activity=" + mActivity);
}
public void testOrienationChange(){
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getInstrumentation().waitForIdleSync();
MyActivity newActivity = getActivity(); //should be new, but it's not
Log.v(TAG, "testOrienationChange; activity=" + newActivity);
}
}
活动:
public class MyActivity extends Activity {
private static final String TAG = "RAMPS";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate; activity=" + this);
setContentView(new TextView(this));
}
//...rest of stuff like onSaveInstanceState() etc.
}
和日志:
06-11 14:16:52.431: V/RAMPS(367): onCreate; activity=MyActivity@44eb8690
06-11 14:16:52.891: V/RAMPS(367): setUp; activity=MyActivity@44eb8690
06-11 14:16:52.971: V/RAMPS(367): onCreate; activity=MyActivity@44ee5178
06-11 14:16:53.131: V/RAMPS(367): testOrienationChange; activity=MyActivity@44eb8690
如前所述,日志显示确实创建了新活动(MyActivity@44ee5178),但 getActivity() 返回在 setUp() 中创建的旧活动(MyActivity@44eb8690)。是否可以访问新创建的?