我的应用程序在启动时有一个 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/