簡體   English   中英

在測試環境中使用findViewById()時返回null?

[英]findViewById() returns null while using it in test clas?

我在片段中有一個布局(main_layout)。 現在,當我嘗試使用以下方法從測試類訪問它時:

View testLayout=getActivity().findViewById(R.layout.main_layout);

它返回我為空嗎? 誰能告訴我我做錯了什么嗎?

我認為您對視圖和布局資源有些困惑。 如果要以“視圖”的形式獲取布局,則可以這樣進行:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.main_layout, null);

或者,如果您想在布局中獲取視圖(請確保已為其指定ID,例如android:id =“ @ + id / textview01”),則可以執行以下操作:

setContentView(R.layout.main_layout);
TextView textView = (TextView) findViewById(R.id.textview01);

您將在main_layout.xml中獲得TextView

試試這個

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main_layout, container, false);

您應該通過id引用視圖,因此應該使用類似R.id.main_layout視圖,而不是使用R.layout.main_layout

首先,在您的main_layout.xml文件中為頂層布局設置一個ID。 例如,id可以為@+id/main_layout_wrapper

然后在測試類中使用以下命令進行搜索:

View testLayout = getActivity().findViewById(R.id.main_layout_wrapper);

此類錯誤由以下幾點引起:

  1. 您是否在setContentView()中使用相同的布局。
  2. 您使用的是相同的小部件ID。

因此,請正確檢查您的活動並使用調試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM