2010-03-20 178 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瞭解佈局屬性。