FragmentPagerAdapter,为什么我需要getPageTitle()

时间:2017-01-20 00:35:47

标签: android

对于我的TabLayout,我有这个FragmentPagerAdapter:

    package de.financeplanner.util.adapter;

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

import de.financeplanner.fragment.OverviewFragment;

/**
 * Created by Christian on 20.01.2017.
 */

public class PagerAdapter extends FragmentPagerAdapter {

    private final int OVERVIEW = 0;
    private final int REVENUES = 1;
    private final int EXPENSES = 2;
    private final int CATEGORY = 3;
    private final int PAGE_COUNT = 4;

    private final String tabTitles[] = new String[] { "Übersicht", "Einnahmen", "Ausgaben", "Kategorie" };

    public PagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment;
        switch(position){
            case OVERVIEW: return new OverviewFragment();
            case REVENUES: return new OverviewFragment();
            case EXPENSES: return new OverviewFragment();
            case CATEGORY: return new OverviewFragment();
        }
        return null;
    }

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        return tabTitles[position];
    }

}

没有这个:

public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        return tabTitles[position];
}

我每次都会收到错误。确切地说,我得到了这个例外:

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'java.lang.Class java.lang.Object.getClass()'

为什么会这样?我无法理解,为什么我需要获取页面标题,因为我认为这个过程是getItem(int position)方法。

1 个答案:

答案 0 :(得分:0)

要回答您的直接问题,getPageTitle()用于设置TabLayout标签上显示的文字。

请注意

@Override
public Fragment getItem(int position) {
    Fragment fragment;
    switch(position){
        case OVERVIEW: return new OverviewFragment();
        case REVENUES: return new OverviewFragment();
        case EXPENSES: return new OverviewFragment();
        case CATEGORY: return new OverviewFragment();
    }
    return null;
}

可以简化为

@Override
public Fragment getItem(int position) {
    return new OverviewFragment();
}

当然,在真实应用中,您很可能希望为每个标签创建不同的片段。因此,如果你还没有那么远,保持目前的结构是好的。至少,您应该删除未使用的声明Fragment fragment;