在方向更改后,IllegalStateException片段未创建视图

问题描述 投票:1回答:1

我有一个应用程序有一个主要活动,用户可以从中选择一个项目。这个选择会产生一个片段(TracksActivityFragment),它本身就是另一个列表。选择该列表的项目时,会添加一个DialogFragment的片段。到目前为止这么好,但是当我旋转设备时,AFragment的onCreate()被调用然后DailogFragment's onCreate()被调用,然后它死于IllegalStateException说它死于AFragment's活动线20(setContentView)。

以下是有关该行的活动的一部分:

public class TracksActivity extends AppCompatActivity
{
    private String mArtistName;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tracks); //DIES HERE

这是片段的onCreate

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

    if(savedInstanceState != null)
    {
        //We've got data saved. Reconstitute it
        mTrackRowItemList = savedInstanceState.getParcelableArrayList(KEY_ITEMS_LIST);
    }
}

DialogFragmentTracksFragment中创建如下:

PlayerFragment fragment = PlayerFragment.newInstance(mTrackRowItemList, i, mArtistBitmapFilename);

// The device is smaller, so show the fragment fullscreen
FragmentTransaction transaction = fragMan.beginTransaction();

// For a little polish, specify a transition animation
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

// To make it fullscreen, use the 'content' root view as the container
// for the fragment, which is always the root view for the activity
transaction.add(android.R.id.content, fragment).addToBackStack(null).commit();

这是DialogFragment的onCreate

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

    if (savedInstanceState != null)
    {
        //We've got data saved. Reconstitute it
        if (mPlayer != null)
        {
            mPlayer.seekTo(savedInstanceState.getInt(KEY_SONG_POSITION));
        }
    }
}

不知道为什么它会回到TracksFragment,因为它有DialogFragment在旋转时有效,但是既然如此,看起来我需要重新创建整个DialogPlayer对象,但它似乎保持这个作为对它的调用onCreate发生了。

有人知道这里需要做什么吗?

android android-fragments illegalstateexception orientation-changes
1个回答
1
投票

好的,之前有人问过,但我打折了解决方案......我不应该这样做。

出于某种原因,Android希望Tracks布局XML使用FrameLayout而不是片段。

所以,只需在layout xml文件中用FrameLayout替换fragment,一切都很好。

© www.soinside.com 2019 - 2024. All rights reserved.