获取在运行时确定的片段页面标题

时间:2012-12-31 00:16:40

标签: android android-fragments

我正在使用包含两个片段的FragmentPagerAdapter。两个片段从AbstractFragment扩展,扩展了Fragment。我无法在创建片段时获取片段的页面标题,因为标题作为参数传递给片段:
 FragmentActivity的内部类:

ArrayList<AbstractFragment> fragments = new ArrayList<AbstractFragment >();
public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            return fragments.get(position);

        }

        @Override
        public int getCount() {

            return fragments.size();


    }

            @Override
            public CharSequence getPageTitle(int position) {

                return fragments.get(position).getTitle();

            }

        }


AbstractFragment:

protected Bundle data;
    protected String title;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        data=this.getArguments();
        numberSetData=data.getParcelableArrayList(KEY_CHART_DATA);
        title=data.getString(KEY_CHART_TITLE);
        //Title should is determined here.
    }
public abstract String getTitle();

ConcreteFragment:

@Override
    public String getTitle(){
        return title;
    }

enter image description here

如果我滑动到下一个片段,问题就会解决,标题会出现但不会在创建时出现。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您在getTitle尚未调用onCreate的位置呼叫Fragment。一个已知的解决方法是检查是否已调用onCreate,如果没有,则返回data.getString(KEY_CHART_TITLE)

public String getTitle()
{
    if( title == null )
    {
        title = getArguments().getString(KEY_CHART_TITLE);
    }
    return title;
}