2015-03-31 42 views
0

我有一个布局(main_layout),我膨胀的片段。 现在,当我尝试使用从测试类访问以下内容:findViewById()在测试类中使用它时返回null?

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

它将返回给我空? 任何人都可以告诉我什么是我正在做的错事吗?

+0

邮政所有代码.. – 2015-03-31 07:34:36

+0

内TextView的@alitha发表您的完整代码 – 2015-03-31 07:37:02

+2

你正在通过ID查找视图,并且您正在进行布局。你应该在你的功能 – Jejefcgb 2015-03-31 07:39:52

回答

-1

这种类型的错误原因由以下几点:

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

所以请检查您的活动是否正确,并使用调试。

0

尝试使用此,

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

你应该参考意见通过id,所以不是使用R.layout.main_layout像你应该使用的东西:R.id.main_layout

0

先设置一个ID,顶层布局在您的main_layout.xml文件中。例如,该ID可以是@+id/main_layout_wrapper

然后在您的测试类搜索它使用:

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

这就是我所做的,它返回null – alitha 2015-03-31 09:26:31

+0

在你粘贴的代码中你正在寻找R.LAYOUT.main_layout,但它应该是R.ID.main_layout。你确定你使用的是正确的吗? – Vesko 2015-03-31 09:28:09

+0

嗨,我试着用R.id,但它仍然返回我空,是的这是正确的布局。 – alitha 2015-03-31 10:16:02

1

我想你做出的视野和布局资源有些混乱。 如果你想获得布局视图中,可以像下面这样做:

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

相关问题