调用findViewById()以获取片段视图时出现NullPointerException

时间:2013-09-04 21:18:22

标签: android android-layout android-fragments findviewbyid

我正在尝试设置FragmentStatePagerAdapter以在我的一个类似this example的片段上创建可滚动的标签界面。在我的活动中onCreate

 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.base);

     setVersionString();
     setupActionBar();
     setupNavigationDrawer();
     setupFragments();
}

我将内容视图设置为以下布局(R.layout.base):

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".BaseActivity" >

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/main_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- The navigation drawer -->
    <ListView
        android:id="@+id/nav_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#FFF" />

</android.support.v4.widget.DrawerLayout>

然后我调用以下函数:

private void setupFragments() {
    // Check that the activity is using the correct layout
    if (findViewById(R.id.main_frame) != null) {
        // Initialize the first fragment
        MainFragment firstFrag = new MainFragment();

        // Pass any extras from an intent to the Fragment
        firstFrag.setArguments(getIntent().getExtras());

        // Add the first Fragment to the screen
        getSupportFragmentManager().beginTransaction()
            .add(R.id.main_frame, firstFrag).commit();

        tabsAdapter = firstFrag.getAdapter();
        Log.d("Base.LOG", "tabsAdapter = " + tabsAdapter);
        tabsAdapter.addTab(DummyFragment.class, null);
    }
}

尝试将FragmentStatePagerAdapter设置为片段布局(R.layout.main)中视图的适配器:

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_page"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainFragment" >

    <android.support.v4.view.PagerTitleStrip
        android:id="@+id/pager_title_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="#33b5e5"
        android:textColor="#fff"
        android:paddingTop="4dp"
        android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>

我的片段代码看起来像这样:

private View mView;
private TabbedPagerAdapter mTabPageAdapter;
private ViewPager mTabPager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    Log.d("Main.LOG", "onCreate called");
    mView = inflater.inflate(R.layout.main, container, false);
    Log.d("Main.LOG", "Layout inflated");
    setupTabs();
    Log.d("Main.LOG", "Tabs setup");

    return mView;
}

@Override
public void onResume() {
    super.onResume();
    Log.d("Main.LOG", "onResume called");
}

/** Set up the ViewPager and Adapter to handle the primary tabs */
private void setupTabs() {
    // Initialize the adapter
    mTabPageAdapter = new TabbedPagerAdapter(getActivity(),
            getActivity().getSupportFragmentManager());

    // Initialize the view pager
    mTabPager = (ViewPager) mView.findViewById(R.id.main_page);
    Log.d("Main.LOG", "mTabPager = " + mTabPager);
    Log.d("Main.LOG", "mTabPageAdapter = " + mTabPageAdapter);
    mTabPager.setAdapter(mTabPageAdapter);
}

/* Accessor for TabbedPagerAdapter */
public TabbedPagerAdapter getAdapter() {
    return mTabPageAdapter;
}

当我尝试添加带有NullPointerException的标签时,应用程序强制关闭。日志中的调试消息显示:

  

D / Base.LOG(27173):tabsAdapter = null

在任何片段的调试消息之前显示

。在尝试访问任何视图或子类之前,如何确保布局膨胀?

2 个答案:

答案 0 :(得分:2)

根据我的评论

public class MainFragment extends Fragment
{
    private MainInterface mInterface = null;
    //make sure to set the above somehow

    public interface MainInterface{
        public void onFragmentReady(.....);
    }

    ... //Do regular stuff here

    public void onResume()
    {
        //Do what you need to do in onResume
        if(mInterface != null)
        {
            mInteface.onFragmentReady();
        }
    }
}

这应该可以让你知道片段何时准备就绪,然后你可以进行getTabAdapter调用。

答案 1 :(得分:1)

在调用setContentView(...)之前,您是否在活动的onCreate(...)方法中调用了setupFragments(...)

如果是:您分配给活动的布局是否包含ViewPager?

我的建议:由于您显然在片段中使用ViewPager,请在片段onCreateView(...)方法中初始化 ViewPager

示例:

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

    // ASSUMING your layout.main contains the ViewPager
    View v = inflater.inflate(R.layout.main, container, false);

    ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
    // and so on ...

    return v;
}