2010-03-20 117 views
1

我想为我的Android的RelativeLayout编写单元测试。目前,我的testcode设置情况如下:Android的RelativeLayout单元测试设置

public class SampleRelativeLayoutTest extends AndroidTestCase { 

private ViewGroup testView; 

private ImageView icon; 
private TextView title; 


@Override 
protected void setUp() throws Exception { 
    super.setUp(); 
    // inflate the layout 
    final Context context = getContext(); 
    final LayoutInflater inflater = LayoutInflater.from(context); 
    testView = (ViewGroup) inflater.inflate(R.layout.sample_layout, 
      null); 
    // manually measure and layout 
    testView.measure(500, 500); 
    testView.layout(0, 0, 500, 500); 
    // init variables 
    icon = (ImageView) testView.findViewById(R.id.icon); 
    title = (TextView) testView.findViewById(R.id.title); 
} 

不过,我遇到NullPointerException异常与下面的堆栈跟踪

java.lang.NullPointerException 
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:427) 
at android.view.View.measure(View.java:7964) 
at com.dqminh.test.view.SampleRelativeLayoutTest.setUp(SampleRelativeLayoutTest.java:33) 
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169) 
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154) 
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430) 
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447) 

我应该在我的设置更改()的代码,使测试运行正常吗?

+0

这工作就像一个魅力对我来说: http://stackoverflow.com/a/6086510/1293704 – Primoz990 2012-12-13 11:41:04

回答

1

我有一个Android源代码的副本,但不知道它是否与你在做什么一样(或者对于这个类没有关系)。 onMeasure方法内部的RelativeLayout行427处的NullPointerException异常。我在版本中的这一行是onMeasure方法中第一次访问mLayoutParams实例变量。是否有可能忘记在你的xml布局或类似的东西中添加layout_width和layout_height参数?

+0

谢谢,的确我错过了布局参数。 加入之后: testView.setLayoutParams(new LayoutParams(500,500));代码正常运行:-) – dqminh 2010-03-20 06:02:17

0

如果您将RelativeLayout包装在LinearLayout中,也可以使用。并改为传递Linearlayout。

0

我会做这样的工作:

LayoutParams layoutParams = new LayoutParams(500,500); 
testView.setLayoutParams(layoutParams); 
testView.layout(0, 0, 500, 500); 
0

另一个可能的原因是:你有RelativeLayout的大小和它的孩子们的位置之间循环依赖。例如,您有一个RelativeLayout,其高度设置为WRAP_CONTENT,子设置为ALIGN_PARENT_BOTTOM

下面是RelativeLayout注释:

其中孩子的位置可以在 关系来描述彼此或与母体的布局。为了提高效率, 一次性评估视图之间的关系,因此如果视图Y取决于视图X的位置为 ,请确保视图X在布局中首先出现 。

请注意,您不能在RelativeLayout的大小和子级的位置之间产生循环依赖关系。例如,您不能有一个RelativeLayout其高度设置为WRAP_CONTENT和一个子设置为ALIGN_PARENT_BOTTOM

另请参阅RelativeLayout.LayoutParams了解布局属性。