Using onConfigurationChanged in a fragment

无人久伴 提交于 2019-11-29 17:50:41

问题


I have this code in a fragment

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

}

What I'm trying to do is that, when I rotate the phone, I don't want the methods to be executed again. But I want to call again the xml layout, to load the layout-land folder's xml.

This code does not give any error, just does not work and do not understand the reason ..

I'm really interested in doing it using onConfiguratonChanged

I appreciate any help.

Thanks and regards


回答1:


In onCreateView create FrameLayout - this is the container for you fragmenView. Then create your R.layout.testone and add it to frameLayout.

In onConfigurationChanged clear FrameLayout, create R.layout.testone again and add it to 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);
}

Now all will work as you want!



来源:https://stackoverflow.com/questions/17116602/using-onconfigurationchanged-in-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!