在片段中使用onConfigurationChanged

Ser*_*o76 14 android onconfigurationchanged screen-rotation android-fragments

我在片段中有这个代码

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

}
Run Code Online (Sandbox Code Playgroud)

我想要做的是,当我旋转手机时,我不希望再次执行这些方法.但我想再次调用xml布局,以加载layout-land文件夹的xml.

这段代码不会给出任何错误,只是不起作用而且不明白原因..

我真的很想使用onConfiguratonChanged来做这件事

我感谢任何帮助.

感谢致敬

Nik*_*Nik 33

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);
}
Run Code Online (Sandbox Code Playgroud)

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