Android中的FragmentManager和屏幕方向变化

3

我不理解Android中的Fragment生命周期,以及屏幕方向改变时会发生什么。

我从Android SDK中的Master-Detail示例开始,然后添加了以下代码:

MyItemListActivity中,我修改了onCreate()函数。

public class MyItemListActivity extends FragmentActivity implements
    MyItemListFragment.Callbacks {

/**
 * Whether or not the activity is in two-pane mode, i.e. running on a tablet
 * device.
 */
private boolean mTwoPane;

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

    FragmentManager fragMgr = getSupportFragmentManager();
    MyItemListFragment oldFragment = (MyItemListFragment)fragMgr.findFragmentByTag("booFragment");

    if (null == oldFragment) {
        FragmentTransaction xact = fragMgr.beginTransaction();
        MyItemListFragment newFragment = MyItemListFragment.createInstance("boo");
        xact.add(
            R.id.myitem_list,
            newFragment,
            "booFragment");
        xact.commit();        
    }

    setContentView(R.layout.activity_myitem_list);

    if (findViewById(R.id.myitem_detail_container) != null) {
        // The detail container view will be present only in the
        // large-screen layouts (res/values-large and
        // res/values-sw600dp). If this view is present, then the
        // activity should be in two-pane mode.
        mTwoPane = true;

        // In two-pane mode, list items should be given the
        // 'activated' state when touched.
        ((MyItemListFragment) getSupportFragmentManager().findFragmentById(
                R.id.myitem_list)).setActivateOnItemClick(true);
    }

    // TODO: If exposing deep links into your app, handle intents here.
}

/**
 * Callback method from {@link MyItemListFragment.Callbacks} indicating that
 * the item with the given ID was selected.
 */
@Override
public void onItemSelected(String id) {
    if (mTwoPane) {
        // In two-pane mode, show the detail view in this activity by
        // adding or replacing the detail fragment using a
        // fragment transaction.
        Bundle arguments = new Bundle();
        arguments.putString(MyItemDetailFragment.ARG_ITEM_ID, id);
        MyItemDetailFragment fragment = new MyItemDetailFragment();
        fragment.setArguments(arguments);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.myitem_detail_container, fragment).commit();

    } else {
        // In single-pane mode, simply start the detail activity
        // for the selected item ID.
        Intent detailIntent = new Intent(this, MyItemDetailActivity.class);
        detailIntent.putExtra(MyItemDetailFragment.ARG_ITEM_ID, id);
        startActivity(detailIntent);
    }
}
}

MyItemListFragment中,我创建了createInstance()

public class MyItemListFragment extends ListFragment {

/**
 * The serialization (saved instance state) Bundle key representing the
 * activated item position. Only used on tablets.
 */
private static final String STATE_ACTIVATED_POSITION = "activated_position";

/**
 * The fragment's current callback object, which is notified of list item
 * clicks.
 */
private Callbacks mCallbacks = sDummyCallbacks;

/**
 * The current activated item position. Only used on tablets.
 */
private int mActivatedPosition = ListView.INVALID_POSITION;

/**
 * A callback interface that all activities containing this fragment must
 * implement. This mechanism allows activities to be notified of item
 * selections.
 */
public interface Callbacks {
    /**
     * Callback for when an item has been selected.
     */
    public void onItemSelected(String id);
}

/**
 * A dummy implementation of the {@link Callbacks} interface that does
 * nothing. Used only when this fragment is not attached to an activity.
 */
private static Callbacks sDummyCallbacks = new Callbacks() {
    @Override
    public void onItemSelected(String id) {
    }
};

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public MyItemListFragment() {
}

public static MyItemListFragment createInstance(String boo) {
    Bundle init = new Bundle();
    init.putString(
        "booboo",
        boo);

    MyItemListFragment frag = new MyItemListFragment();
    frag.setArguments(init);
    return frag;
}

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

    // TODO: replace with a real list adapter.
    setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
            android.R.layout.simple_list_item_activated_1,
            android.R.id.text1, DummyContent.ITEMS));
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Restore the previously serialized activated item position.
    if (savedInstanceState != null
            && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
        setActivatedPosition(savedInstanceState
                .getInt(STATE_ACTIVATED_POSITION));
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // Activities containing this fragment must implement its callbacks.
    if (!(activity instanceof Callbacks)) {
        throw new IllegalStateException(
                "Activity must implement fragment's callbacks.");
    }

    mCallbacks = (Callbacks) activity;
}

@Override
public void onDetach() {
    super.onDetach();

    // Reset the active callbacks interface to the dummy implementation.
    mCallbacks = sDummyCallbacks;
}

@Override
public void onListItemClick(ListView listView, View view, int position,
        long id) {
    super.onListItemClick(listView, view, position, id);

    // Notify the active callbacks interface (the activity, if the
    // fragment is attached to one) that an item has been selected.
    mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (mActivatedPosition != ListView.INVALID_POSITION) {
        // Serialize and persist the activated item position.
        outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
    }
}

/**
 * Turns on activate-on-click mode. When this mode is on, list items will be
 * given the 'activated' state when touched.
 */
public void setActivateOnItemClick(boolean activateOnItemClick) {
    // When setting CHOICE_MODE_SINGLE, ListView will automatically
    // give items the 'activated' state when touched.
    getListView().setChoiceMode(
            activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
                    : ListView.CHOICE_MODE_NONE);
}

private void setActivatedPosition(int position) {
    if (position == ListView.INVALID_POSITION) {
        getListView().setItemChecked(mActivatedPosition, false);
    } else {
        getListView().setItemChecked(position, true);
    }

    mActivatedPosition = position;
}
}

应用程序在启动时运行良好,但当我旋转屏幕时,应用程序崩溃,并且日志中出现以下内容:
``` 12-12 13:41:23.930: E/AndroidRuntime(31051): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mymasterdetail/com.example.mymasterdetail.MyItemListActivity}: android.view.InflateException: Binary XML file line #24: Error inflating class fragment ... 12-12 13:41:23.930: E/AndroidRuntime(31051): Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class fragment 12-12 13:41:23.930: E/AndroidRuntime(31051): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713) ... 12-12 13:41:23.930: E/AndroidRuntime(31051): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290) 12-12 13:41:23.930: E/AndroidRuntime(31051): at android.app.Activity.setContentView(Activity.java:1928) 12-12 13:41:23.930: E/AndroidRuntime(31051): at com.example.mymasterdetail.MyItemListActivity.onCreate(MyItemListActivity.java:52) ... ```
(第52行是 Activity 中的`setContentView()`调用。)
如果我移除`xact.add()`,则应用程序可以正常运行。 (但是没有数据传递到 Fragment。)
我知道使用 FragmentTransaction 方法将数据传递到我的 Fragment 是正确的,但我不知道还需要做什么来准备 Fragment 处理与屏幕方向更改相关的生命周期事件,并且我不知道如何填充 Fragment(隐式地或显式地)。
(我正在使用平板电脑,因此具有两个面板显示,如果有区别,请告诉我。)

请参见http://stackoverflow.com/questions/20413856/properly-interacting-with-fragments-in-fragmentpageradapter/20414354#20414354,看看 "OnSaveinstanceState()"。你需要以一种API可以检索到数据所属的片段的方式存储试图传递给 xact.add 的 bundle,在方向更改时。使用方向更改API传递数据,而不是显式调用。 - Robert Rowntree
3个回答

0

尝试将setContentView()移动到在实例化片段之前。

如果您先设置片段并尝试将它们附加到尚不存在的视图,则可能会出现错误。

还要确保您附加片段的视图存在于您的纵向和横向布局中。

由于您正在以编程方式添加片段,请确保不要在XML布局中添加它们。您的布局中应该只有一个FrameLayout,用于附加片段。


那没有任何效果。仍然崩溃。 - AnotherStupidUser
那么问题可能不在你已经发布的代码中,这些代码非常标准(除了已经提到的setContentView问题)。也许你应该发布完整的代码而不是只有片段。 - Kuffs
这是我写的唯一代码。除此之外,我使用了SDK示例代码并未进行修改。 - AnotherStupidUser
由于SDK代码可以工作而你的代码不能,明智的做法是查看差异和你所做的更改。 - Kuffs
你上一条评论给了我提示 - “由于你是以编程方式添加片段,请确保不要在XML布局中也添加它们。” 我检查了一下是否存在findFragmentById,如果存在,我会调用xact.replace()而不是xact.add()。谢谢。 - AnotherStupidUser

0

屏幕方向改变时会发生什么是当前活动被销毁并重新创建 - 这很有用,因为可以填充替代布局(如果您在资源文件夹中有另一个方向的布局)。

可能在这里发生的是,在充气之前尝试访问片段(如Kuffs所说)。


0

你的片段需要一个公共的空构造函数。

来自http://developer.android.com/reference/android/app/Fragment.html

所有Fragment的子类都必须包含一个公共的空构造函数。框架通常会在需要时重新实例化一个片段类,特别是在状态恢复期间,并且需要能够找到此构造函数来实例化它。如果空构造函数不可用,则在某些情况下,在状态恢复期间将发生运行时异常。


我有一个空构造函数: public MyItemListFragment() { } - AnotherStupidUser
如果您发布完整的堆栈跟踪信息将会很有帮助。使用“adb logcat -s AndroidRuntime:E”命令可以为您生成该信息。 - Steve Prentice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接