方向更改时未添加片段

时间:2014-10-27 18:57:52

标签: android android-fragments android-orientation illegalstateexception screen-rotation

我正在使用这样的片段:

public class MyFragment extends Fragment implements MyListener {

    private String name, id;

    public MyFragment(){
    }

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

        if (savedInstanceState != null) {
            Log.d(TAG, "Restoring saved state");
            // Restore id & name
            ....
        }
    }

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

        View v = inflater.inflate(R.layout.my_fragment, container, false);  
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // do stuff with AsyncHttpClient that will call "onResponseReady" after some time
    }

    @Override
    public void onResponseReady() {

        if (!isAdded()) {
            Log.d(TAG, "Fragment not added");
            return;
        }
        Log.d(TAG, "Fragment added");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString(KEY_ID, this.id);
        outState.putString(KEY_NAME, this.name);
    }
}

当我启动应用程序时,我在LogCat中收到Fragment added消息,但是如果我旋转设备然后我得到Fragment not added,那么如果我尝试访问某些视图(例如,在my_fragment.xml)我得到IllegalStateException: Fragment MyFragment not attached to Activity

为什么在方向更改后片段没有附加到活动?

0 个答案:

没有答案