gpt4 book ai didi

android-layout - 为什么在 Robolectric 中内容 View 的高度和宽度为零?

转载 作者:行者123 更新时间:2023-12-05 07:59:58 26 4
gpt4 key购买 nike

这是一个失败的测试:

@RunWith(RobolectricTestRunner.class)
public class FailTest {

@Test
public void heightAndWidth_shouldNotBeZero() {
TestActivity testActivity = Robolectric.buildActivity(TestActivity.class).create().resume().visible().get();
View contentView = testActivity.findViewById(69);
Assertions.assertThat(contentView.getWidth()).isNotZero();
Assertions.assertThat(contentView.getHeight()).isNotZero();
}

private static class TestActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout contentView = new LinearLayout(this);
contentView.setId(69);
contentView.setLayoutParams(new LayoutParams(666, 666));
setContentView(contentView);
}
}
}

如您所见,我在 ActivityControllerdriving the Activity lifecycle 上调用了 visible() 方法。正确的方法。引用文档:

Wait, What's This visible() Nonsense?

Turns out that in a real Android app, the view hierarchy of an Activity is not attached to the Window until sometime after onCreate() is called. Until this happens, the Activity's views do not report as visible. This means you can't click on them (amongst other unexpected behavior). The Activity's hierarchy is attached to the Window on a device or emulator after onPostResume() on the Activity. Rather than make assumptions about when the visibility should be updated, Robolectric puts the power in the developer's hands when writing tests.

So when do you call it? Whenever you're interacting with the views inside the Activity. Methods like Robolectric.clickOn() require that the view is visible and properly attached in order to function. You should call visible() after create().

似乎我正在做我需要做的一切。那为什么我没有高度/宽度?​​

最佳答案

Robolectric 中没有布局 channel ,因此 View 尺寸始终为零。

https://github.com/robolectric/robolectric/issues/819

关于android-layout - 为什么在 Robolectric 中内容 View 的高度和宽度为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19829469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com