应用程序关闭viewPager.setAdapter(适配器)

时间:2014-12-23 11:08:18

标签: android android-viewpager fragmentmanager

我有一个包含两个片段的viewpager的应用程序页面。 当我的活动弹出时,会发出服务器请求以加载当前数据,然后设置适配器。 但该应用程序崩溃时出现以下错误。

尝试调用虚方法' void android.support.v4.app.Fragment.setMenuVisibility(boolean)'在空对象引用上

在调试时,viewPager.setAdapter(adapter)显示空指针异常。我的viewPager既不是null也不是我的适配器。

我无法弄清楚为什么会这样。

请帮忙!! 在此先感谢!!

2 个答案:

答案 0 :(得分:18)

发现问题..在我的fragmentPagerAdapter中,getItem()为片段返回null。

答案 1 :(得分:1)

试试这段代码

创建一个类文件TabOne.java

package com.example.tabfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TabOne extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab_one, null);

    return rootView;
}
}

创建一个类文件TabTwo.java

package com.example.tabfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TabTwo extends Fragment {

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

    View rootView = inflater.inflate(R.layout.tab_two, null);
    return rootView;
}

}

**创建xml文件tab_one.xml和tab_two.xml **

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:text="@string/tab_2" />

</RelativeLayout>

创建一个TabFragmentPageAdapter.java类

package com.example.tabfragment;

import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;

public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments,
        Bundle args) {
    super(fm);
    this.fragments = fragments;
    this.args = args;
}

@Override
public Fragment getItem(int position) {
    Fragment fragment = fragments.get(position);
    fragment.setArguments(args);
    return fragment;
}

@Override
public int getCount() {
    return fragments.size();
}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}
}

创建一个类文件TabFragments.java

public class TabFragments extends Fragment implements OnPageChangeListener,
    OnTabChangeListener {

public static final int TAB_LOGIN = 0;
public static final int TAB_REG = 1;

private TabHost tabHost;
private int currentTab = TAB_LOGIN;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, null);
    tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
    viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
    viewPager.setOnPageChangeListener(this);
    fragments = new ArrayList<Fragment>();
    fragments.add(new TabOne());
    fragments.add(new TabTwo());


    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);
    pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
            fragments, getArguments());
    pageAdapter.notifyDataSetChanged();
    viewPager.setAdapter(pageAdapter);
    setupTabs();

}

private void setupTabs() {
    tabHost.setup();
    tabHost.addTab(newTab(R.string.tab_1));
    tabHost.addTab(newTab(R.string.tab_2));


    for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {

        tabHost.getTabWidget().getChildAt(i)
                .setBackgroundColor(Color.parseColor("#304c58"));

        // tabHost.setBackgroundResource(R.drawable.tab_selector);
        final View view = tabHost.getTabWidget().getChildTabViewAt(i);
        final View textView = view.findViewById(android.R.id.title);
        ((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));

        ((TextView) textView).setSingleLine(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            tabHost.getTabWidget().getChildAt(i)
                    .findViewById(android.R.id.icon);
            tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;

        } else {

            if (view != null) {
                // reduce height of the tab
                view.getLayoutParams().height *= 0.77;

                if (textView instanceof TextView) {
                    ((TextView) textView).setGravity(Gravity.CENTER);
                    textView.getLayoutParams().height =  ViewGroup.LayoutParams.MATCH_PARENT;
                    textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
                }
            }
        }

    }
    tabHost.setOnTabChangedListener(TabFragments.this);
    tabHost.setCurrentTab(currentTab);
}

private TabSpec newTab(int titleId) {
    TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
    tabSpec.setIndicator(getString(titleId));
    tabSpec.setContent(new TabFactory(getActivity()));
    return tabSpec;
}

@Override
public void onPageScrollStateChanged(int position) {

}

@Override
public void onPageScrolled(int position, float arg1, int arg2) {

}

@Override
public void onPageSelected(int position) {
    tabHost.setCurrentTab(position);
}

@Override
public void onTabChanged(String tabId) {
    currentTab = tabHost.getCurrentTab();
    viewPager.setCurrentItem(currentTab);
    updateTab();
}

@SuppressWarnings("unused")
private void updateTab() {
    switch (currentTab) {
    case TAB_LOGIN:
        TabOne login = (TabOne) fragments.get(currentTab);
        break;
    case TAB_REG:
        TabTwo register = (TabTwo) fragments
                .get(currentTab);
        break;
    }
}

class TabFactory implements TabContentFactory {

    private final Context context;

    public TabFactory(Context context) {
        this.context = context;
    }

    @Override
    public View createTabContent(String tag) {
        View v = new View(context);
        v.setMinimumHeight(0);
        v.setMinimumWidth(0);
        return v;
    }

}
}

创建活动类

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

public class MainActivity extends ActionBarActivity {

Fragment fragment = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fragment = new TabFragments();

    Log.i("fragment", "" + fragment.getId());

    if (fragment != null) {
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction().replace(R.id.frame_container, fragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                .commit();
    }
}

}

创建mainactivity.xml文件

 <?xml version="1.0" encoding="utf-8"?>
 <android.support.v4.widget.DrawerLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >  

      <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       />
 </android.support.v4.widget.DrawerLayout>

创建标签片段_home.xml文件

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ts="http://schemas.android.com/apk/res-auto"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fadingEdge="none"
        android:background="#394c58"
        android:tabStripEnabled="false" />

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

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
</LinearLayout>

</TabHost>