創建你FragmentPagerAdapter
自己setTitle
方法。這裏有一個例子:
FragmentPagerAdapter
public class PagerAdapter extends FragmentPagerAdapter {
/** A @ {@link List} of each {@link Fragment} displayed */
private final List<Fragment> mFragments = new ArrayList<Fragment>();
/** The titles for the underlying {@link PagerTitleStrip} */
private final List<String> mTitles = new ArrayList<String>();
/**
* Constructor for <code>PagerAdapter</code>
*
* @param fm The {@link FragmentManager} to use
*/
public PagerAdapter(FragmentManager fm) {
super(fm);
}
/**
* {@inheritDoc}
*/
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
/**
* {@inheritDoc}
*/
@Override
public int getCount() {
return mFragments.size();
}
/**
* {@inheritDoc}
*/
@Override
public CharSequence getPageTitle(int position) {
return mTitles.get(position);
}
/**
* Adds a new {@link Fragment} and title to the adapter
*
* @param fragment The {@link Fragment} to add
* @param title The title for the {@link Fragment}
*/
public void add(Fragment fragment, String title) {
mFragments.add(fragment);
mTitles.add(title);
notifyDataSetChanged();
}
/**
* Removes each {@link Fragment} from the adapter
*/
public void clear() {
mFragments.clear();
mTitles.clear();
notifyDataSetChanged();
}
}
LoaderCallback
private PagerAdapter mAdapter;
/**
* {@inheritDoc}
*/
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
final Uri uri = Audio.Artists.EXTERNAL_CONTENT_URI;
final String[] projection = new String[] {
BaseColumns._ID, ArtistColumns.ARTIST
};
return new CursorLoader(this, uri, projection, null, null, null);
}
/**
* {@inheritDoc}
*/
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
while (data != null && data.moveToNext()) {
final String artist = data.getString(1);
mAdapter.add(new DummyFragment(), artist);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.clear();
}
我使用的DummyFragment
不過是FrameLayout
。
這是一種方法,另一種方法是使用Fragment.getArguments
。事情是這樣的:
FragmentPagerAdapter
/**
* {@inheritDoc}
*/
@Override
public CharSequence getPageTitle(int position) {
return getItem(position).getArguments().getString("your_key");
}
LoaderCallback
/**
* {@inheritDoc}
*/
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
while (data != null && data.moveToNext()) {
final String artist = data.getString(1);
final Bundle args = new Bundle();
args.putString("your_key", artist);
final DummyFragment fragment = new DummyFragment();
fragment.setArguments(args);
mAdapter.add(fragment);
}
}
所以,有一對夫婦,但實際上你需要的是某種回調到PagerAdapter.getPageTitle
。
在一個冒險的嘗試中,你可以簡單地引用'PagerTitleStrip'並遍歷它的子節點(應該是3)並將它們轉換爲'TextViews'並直接設置文本。你爲什麼要設置這麼快的標題? – Luksprog
我做一個即時搜索,並顯示每個片段上顯示的搜索結果的數量作爲其標題的一部分。 – cody