findViewById()在测试类中使用它时返回null?

时间:2015-03-31 07:33:58

标签: android testing view findviewbyid

我有一个我在片段中膨胀的布局(main_layout)。 现在,当我尝试使用以下方法从测试类访问它时:

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

它返回给我null? 谁能告诉我,我做错了什么?

5 个答案:

答案 0 :(得分:1)

我认为你对View和layout资源有些困惑。 如果你想把布局作为View,你可以这样做:

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中的T​​extView

答案 1 :(得分:0)

尝试使用它,

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

答案 2 :(得分:0)

您应该id引用视图,因此您应该使用R.layout.main_layout

之类的内容,而不是R.id.main_layout

答案 3 :(得分:0)

首先将ID设置为main_layout.xml文件中的顶级布局。例如,id可以是@+id/main_layout_wrapper

然后在您的测试类中使用以下方法搜索它:

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

答案 4 :(得分:-1)

此类错误由以下几点引起:

  1. 您是否在setContentView()中使用相同的布局。
  2. 您正在使用相同的小部件ID。
  3. 因此,请正确检查您的活动并使用调试。