我正在编写片段的程序,其中我在potrait模式下有一个片段,在横向模式下有两个片段。 mainfrag1包含一个纵向片段和两个横向模式片段。 fr1和fr2是片段1和片段2的ID 当我将活动从纵向切换到横向时,按照下面的代码
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainfrag1);
FragmentManager fm=getFragmentManager();
try
{
f2=(Fragment)fm.findFragmentById(R.id.fr2);
}catch(Exception ep){}
if(f2!=null)
{
Toast.makeText(this, "it is both", Toast.LENGTH_SHORT).show();
et=(EditText)f2.getView().findViewById(R.id.editText1);
}
else
Toast.makeText(this, "it is only one", Toast.LENGTH_SHORT).show();
}
当我们从横向移回肖像但f2.getView返回null时,check f2!= null返回true。 为什么f2不在屏幕上时不给出null,如何更新代码以使其正常运行 请清楚这一点。 感谢
答案 0 :(得分:0)
保留的片段在创建时可能没有视图。 Fragment通过一个类似于Activity生命周期的生命周期,因此它将被销毁,然后在适当的时候再次创建。
但是,如果您尝试从片段中获取特定视图,则会出现设计错误,您应该让Fragment自行处理它。