Java findViewById()在片段中返回null的另一个例子
是的,我知道关于findViewById()返回null和no的问题有几个主题,它们似乎都不能解决我的问题 大多数解决方案都是关于调用Java findViewById()在片段中返回null的另一个例子,java,android,android-fragments,Java,Android,Android Fragments,是的,我知道关于findViewById()返回null和no的问题有几个主题,它们似乎都不能解决我的问题 大多数解决方案都是关于调用findViewId()的时间,我认为这不是我的情况 因此,我有一个MyFragment类,用于显示在ViewPager上的片段。该类遵循建议的创建模式(使用newInstance()方法) 在我的onCreateView方法中,我在新扩展的视图(rootView)中找到了一些视图,设置了一些属性(字体、文本…)和侦听器。其中一个视图(在本例中,problemat
findViewId()
的时间,我认为这不是我的情况
因此,我有一个MyFragment
类,用于显示在ViewPager
上的片段。该类遵循建议的创建模式(使用newInstance()
方法)
在我的onCreateView
方法中,我在新扩展的视图(rootView
)中找到了一些视图,设置了一些属性(字体、文本…)和侦听器。其中一个视图
(在本例中,problematicLayout
)应该是可视/隐藏的,具体取决于条件
在我旋转设备之前,一切正常。在我旋转设备的过程中,onCreateView()
中的所有视图都被正确找到并设置了它们的属性problematicLayout=(LinearLayout)rootView.findViewById(R.id.problematicLayout)
返回的是null
。如果我暂停并浏览视图层次结构
(rootView-->mChildren-->等等)我可以看到problematicallayout
有它的ID=-1代码>
我还尝试使用方法签名的视图,将我的findViewById(R.id.problematicLayout)
移动到onViewCreated()
,结果相同
如果我对行进行了注释,并且从未使problematicLayout
不可见/消失,那么我就不会有同样的问题
为什么会这样?为什么将problematicLayout的ID设置为-1,导致findViewById()
返回null?我错过了什么
public static Fragment newInstance(Context context,
int position, Answer answer) {
MyFragment frag = new MyFragment ();
Bundle args = new Bundle();
args.putParcelable(STUFF NAME, STUFF);
frag.setArguments(args);
return frag;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.my_fragment, container, false);
ScorllView someScrollView = (ScrollView) rootView.findViewById(R.id.someScrollView);
// ... other views, setting their event listners, etc.
LinearLayout problematicLayout = (LinearLayout ) rootView.findViewById(R.id.problematicLayout);
setProblematicLayout(problematicLayout);
// ... setting other listeners, etc.
return rootView;
}
public void setProblematicLayout(LinearLayout layout)
{
if(!condition)
{
layout.setVisibiliy(View.GONE)
// ... set listeners and properties for views inside the layout.
}
else
{
layout.setVisibiliy(View.INVISIBLE);
}
}
如果您正在为纵向/横向使用布局资源变体,请确保在这两个视图中都找到视图。您确定所述布局位于my_fragment.xml
中吗?您是否有布局的横向/纵向变体,并且视图仅位于另一个视图中?请添加布局文件Yep。否则,我会立即得到异常,而不仅仅是在旋转设备之后。D'oh@laalto。你说得对。我忘了在布局的横向变体中设置“problematiclayout”的id!你可以输入答案,我会接受的。是的,我已经忘记了这个特殊的布局。哑巴时刻,谢谢(8分钟后接受)。