Fragment setRetainInstance not works (Android support lib) [duplicate]

你离开我真会死。 提交于 2019-12-08 12:08:51

问题


Possible Duplicate:
Android fragments setRetainInstance(true) not works (Android support library)

I wrote a simple test project, but I cant understand why I always receive savedInstanceState = null in lifecycle methods onCreate, onCreateView and onActivityCreated. I change the screen orientation, see the log, but state not saved. Tell me please where is my mistake. Thanks. The code of fragment class is:

public class TestFragment extends Fragment {

private String state = "1";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        //never works
        state = savedInstanceState.getString("state");
    }
    //always prints 1
    Toast.makeText(getActivity(), state, Toast.LENGTH_SHORT).show();
    return inflater.inflate(R.layout.fragment_layout, container, false);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("state", "2");
    Log.e("", "saved 2");
}

}

EDIT

When i try to use setRetainInstance i have no result again((( I change a state to 2 using btn1, but after changing orientation i see 1 when pressing on btn2. Help please(

public class TestFragment extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
    setRetainInstance(true);
    super.onCreate(savedInstanceState);
}

private String state = "1";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_layout, container, false);

    //button for changing state
    ((Button)view.findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            state = "2";
        }
    });

    //button for showing state
    ((Button)view.findViewById(R.id.button2)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            Toast.makeText(getActivity(), state, Toast.LENGTH_SHORT).show();
        }
    });

    return view;
}

}


回答1:


I have seen the same issue. But you can save the instate state in an other way, thanks to the method setRetainInstance(true), all your class data are saved automatically.

@Override
public void onCreate(Bundle savedInstanceState) {
    setRetainInstance(true);
    super.onCreate(savedInstanceState);
}

EDIT

Try to also add these params when you declare your activities :

    <activity
        android:name="MyActivity"
        android:configChanges="orientation|keyboardHidden|screenSize" />


来源:https://stackoverflow.com/questions/12898901/fragment-setretaininstance-not-works-android-support-lib

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