17

我在片段中有这段代码

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 非常感兴趣

我很感激任何帮助。

谢谢并恭祝安康

4

1 回答 1

34

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

现在一切都会如你所愿!

于 2013-07-01T11:25:55.200 回答