使用ViewPager适配器更改操作栏标题

时间:2013-07-18 11:13:33

标签: android android-viewpager fragment

目前我正在尝试开发一个实现不同视图之间滑动的应用程序。 滑动工作正常,但我想将视图的标题设置为操作栏,用户知道他在哪里。

所以我希望你能给我一些想法,我必须把代码换成标题。

由于

2 个答案:

答案 0 :(得分:1)

您需要为ViewPager设置OnPageChangeListener。当您滑动时,系统会通知OnPageChangeListener,您可以从回调中更改ActionBar标题。

这里有一些伪代码:

ViewPager vp;
vp.setOnPageChangeListener(new OnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
        getActionBar().setTitle(titles[position]); // Set the correct title based on the position
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} // not used

    @Override
    public void onPageScrollStateChanged(int state) {} // not used
});

答案 1 :(得分:0)

public void setTitle (CharSequence title)

Change the title associated with this activity. If this is a top-level activity, the title for its window will change. If it is an embedded activity, the parent can do whatever it wants with it.

http://developer.android.com/reference/android/app/Activity.html#setTitle(int)

mPager.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int pos) {
                    // Chage the title
                }


                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    // TODO Auto-generated method stub

                }
            });