在片段中使用onConfigurationChanged

时间:2013-06-14 20:16:12

标签: android android-fragments screen-rotation onconfigurationchanged

我在片段中有这段代码

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

我感谢任何帮助。

谢谢和问候

1 个答案:

答案 0 :(得分:31)

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);
}

现在一切都会按你的意愿运作!