我有一个片段中的这段代码
public class TestOne extends Fragment {
View view = null;
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LayoutInflater inflater2 = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater2.inflate(R.layout.testone, null);
Toast.makeText(getActivity(), "Rotate fragment", Toast.LENGTH_SHORT).show();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getActivity(), "onCreate Fragment", Toast.LENGTH_SHORT).show();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
view = inflater.inflate(R.layout.testone, null);
Toast.makeText(getActivity(), "onCreateView fragment", Toast.LENGTH_SHORT).show();
return view;
}
}
我想做的是,当我旋转手机时,我不想再次执行这些方法。但是我想再次调用xml布局,以加载layout-land文件夹的xml。
这段代码没有给出任何错误,只是不起作用并且不了解原因..
我真的对使用onConfiguratonChanged做到这一点很感兴趣
感谢您的帮助。
感谢致敬
最佳答案
在onCreateView
中创建FrameLayout
-这是您fragmenView
的容器。然后创建您的R.layout.testone
并将其添加到frameLayout
。
在onConfigurationChanged
中清除FrameLayout
,再次创建R.layout.testone
并将其添加到frameLayout
中。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
frameLayout = new FrameLayout(getActivity());
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.testone, null);
frameLayout .addView(view);
return frameLayout;
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
frameLayout. removeAllViews();
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.testone, null);
frameLayout .addView(view);
}
现在一切都将按您的意愿工作!