我有一个布局(main_layout),我膨胀的片段。 现在,当我尝试使用从测试类访问以下内容:findViewById()在测试类中使用它时返回null?
View testLayout=getActivity().findViewById(R.layout.main_layout);
它将返回给我空? 任何人都可以告诉我什么是我正在做的错事吗?
我有一个布局(main_layout),我膨胀的片段。 现在,当我尝试使用从测试类访问以下内容:findViewById()在测试类中使用它时返回null?
View testLayout=getActivity().findViewById(R.layout.main_layout);
它将返回给我空? 任何人都可以告诉我什么是我正在做的错事吗?
这种类型的错误原因由以下几点:
所以请检查您的活动是否正确,并使用调试。
尝试使用此,
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main_layout, container, false);
你应该参考意见通过id
,所以不是使用R.layout.main_layout
像你应该使用的东西:R.id.main_layout
先设置一个ID,顶层布局在您的main_layout.xml
文件中。例如,该ID可以是@+id/main_layout_wrapper
。
然后在您的测试类搜索它使用:
View testLayout = getActivity().findViewById(R.id.main_layout_wrapper);
我想你做出的视野和布局资源有些混乱。 如果你想获得布局视图中,可以像下面这样做:
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
邮政所有代码.. – 2015-03-31 07:34:36
内TextView的@alitha发表您的完整代码 – 2015-03-31 07:37:02
你正在通过ID查找视图,并且您正在进行布局。你应该在你的功能 – Jejefcgb 2015-03-31 07:39:52