android Fragment getActivity()。findViewById导致NullPointerException

时间:2014-04-02 14:34:04

标签: java android android-fragments

在关闭插页式广告横幅(使用“X”或点击“返回”后)时,我在片段中更新我的活动的菜单项时遇到问题。 在android HONEYCOMB之前,插页式横幅之后一切运行良好,也许是因为我使用的是android.support.v4.app.Fragment。

在我的活动中使用此布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <HorizontalScrollView
        android:id="@+id/menuContainer"
        android:layout_width="match_parent"
        android:layout_height="32dp" />

    <FrameLayout
        android:id="@+id/fragments"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

</LinearLayout>

我添加了一个新片段,一切顺利:

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragments, MyFragment.newInstance());
transaction.addToBackStack(null);
transaction.commit();

这是片段代码:

public static MyFragment newInstance() {
    return new MyFragment();
}
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

private View mSimpleContainer;
private TextView mSimpleText;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_test, container, false);

    mSimpleContainer = view.findViewById(R.id.mSimpleContainer);
    mSimpleText = (TextView) view.findViewById(R.id.simpleText);

    return view;
}

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mSimpleText.setText("lorem ipsum");

    MyActivity act = (MyActivity) getActivity();

    if (act != null) {
        HorizontalScrollView menu = (HorizontalScrollView) act.findViewById(R.id.menuContainer);

        /**
        * menu is null and I get NullPointerException here after interstitial is closed.
        * Maybe the activity is paused and resumed but I expect that in onActivityCreated the activity is attached
        */
        menu.hideMenuItems();

        //This line open an Interstitial banner that when it's closed causes NullPointerException above
        act.showInterstitial(); //If I comment this line everything works fine
    }
}

什么时候在活动中调用findViewById? 谢谢你的回答

1 个答案:

答案 0 :(得分:1)

我认为你在片段FrameLayout中切换了许多片段。在那种情况下,片段显示并隐藏。因此,如果发生任何内存不足,fragmentManger会破坏不可见的片段视图,但仍会附加到活动中。所以getActivity()没有返回null,但是视图返回null。在这种情况下,你将调用getView(),如果getView()返回null,那么你的片段视图被fragmentManager破坏,否则调用getView()。findViewById()它将返回有效的视图对象。 support.v4片段没有问题。可能是支持的片段管理器.v4更有记忆性。