android - 使用 ViewPager 设置 Actionbar 标题

标签 android android-viewpager

我的应用程序在启动时有一个 ListView。用户可以手动选择 ListView 中的项目以转到详细信息屏幕,也可以使用 ViewPager 在不同的详细信息屏幕之间滑动。 ViewPager 的 fragment 设置如下:

Listing
Detail 1
Detail 2
Detail 3
Detail 4
...

It's my understanding, when the Listing fragment is loaded, the ViewPager will execute Detail 1's code, for performance. The same when Detail 1 is loaded, Detail 2's code will execute.

The problem I'm running into is that I'm setting the title of each detail fragment in onActivityCreated, however, when the Listing fragment is loaded, it is displaying Detail 1's title. So I moved the code to onPageSelected of the ViewPager, which works if the user is swiping, but if the user manually selects an item in the ListView the title is never set.

I'm not sure if there is an event that is only fired when a user manually selects an item in the ListView and not when they are swiping or if I need to rethink my apps' setup. For example, instead of using this code in the Listing fragment's onListItemClick event:

final Intent listing = new Intent(getActivity().getApplicationContext(), Details.class);
startActivity(listing);

我需要以某种方式使用ViewPager

mViewPager = (ViewPager)findViewById(R.id.viewpager);  
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());  
mViewPager.setAdapter(mMyFragmentPagerAdapter);
mViewPager.setSaveEnabled(false);
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

    @Override
    public void onPageSelected(int position) {      
        String title = GetTitle(position);
        getSupportActionBar().setTitle(title);                  
    }

    @Override
    public void onPageScrolled(int position, float offset, int offsetPixel) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});

最佳答案

您可能想要重写方法 getPageTitle(int)在您的 MyFragmentPagerAdapter 类中。文档指出:

This method may be called by the ViewPager to obtain a title string to describe the specified page. This method may return null indicating no title for this page. The default implementation returns null.

因此,不要返回 null,而是确保返回实际的页面标题。您将获得请求标题的页面的位置/索引,因此一个简单的 switch-case 语句就足够了。或者,您可以为您的页面设置一个界面并查询相关页面的标题。

关于android - 使用 ViewPager 设置 Actionbar 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14427005/

相关文章:

java - ANDROID : give id into widget such as Textview, Edittext,动态行/ View 中的微调器并将其存储到 sqlite 中

java - 返回嵌套 viewpager 时恢复状态会导致崩溃

java - viewpager 中 fragment 中的 Recyclerview

android - 在 ViewPager 位置从 SQLite 表设置 EditText

java - 无法更改嵌套 fragment 中的 ActionBar 标题

android - ListView 中有多个 EditText,点击聚焦一个 EditText,焦点跳转到第一个

java - 为什么 putExtra 采用键值对而不仅仅是一个值?

android - 使用 prefs.xml <ListPreference> 进行颜色更改的 Activity 在启动时崩溃

Android map 叠加层在缩放时消失

android - 我应该为 listfragment 使用什么适配器以及它们应该扩展什么类