我想使用滑动 ViewPager 创建文章列表。在移动过程中,我想动态更改操作栏中的标题。标题存储在字符串列表中,每个列表的标题是当前 fragment 的位置。因此,例如,给定此列表:
List<String> leftItems = new List<String> ();
leftItems.Add ("First title");
leftItems.Add ("Second title");
leftItems.Add ("Third title");
我想在观看 fragment 2(索引 1)时显示标题
Second title
fragment 中操作栏的标题我更改了这段代码:
((ActionBarActivity)Activity).SupportActionBar.Title = this.leftItems[this.position];
GetItem()方法中适配器自带的变量'position':
public override Android.Support.V4.App.Fragment GetItem(int position) {
return new ArticlesFragment (this.articles [this.leftItems [position]],
this.leftItems, this.position);
}
public ArticlesFragment(List<Article> articles, List<String> leftItems, int position) : base() {
this.articles = articles;
this.leftItems = leftItems;
this.position = position;
}
我有什么问题?好吧,操作栏的标题总是比它应该的大一个索引。所以对于 fragment 1(索引 0),标题是
Second title
不是我想要的
First title
但是,在最后一个 fragment 中,标题没有改变,只是与前一个 fragment 保持一致。
有人可以帮助我吗?
@编辑
我添加了适配器的全部内容和一个 fragment :
ArticlesFragmentAdapter.cs
public class ArticlesFragmentAdapter : FragmentStatePagerAdapter {
Dictionary<String, List<Article>> articles;
List<String> leftItems;
public ArticlesFragmentAdapter(Android.Support.V4.App.FragmentManager fm,
Dictionary<String, List<Article>> articles,
List<String> leftItems) : base(fm) {
this.articles = articles;
this.leftItems = leftItems;
}
public override int Count {
get { return this.leftItems.Count; }
}
public override Android.Support.V4.App.Fragment GetItem(int position) {
return new ArticlesFragment (this.articles [this.leftItems [position]],
this.leftItems, position);
}
}
ArticlesFragment.cs
public class ArticlesFragment : Android.Support.V4.App.Fragment {
List<Article> articles;
List<String> leftItems;
ListView articlesListView;
int position;
ArticlesAdapter articlesAdapter;
public ArticlesFragment(List<Article> articles, List<String> leftItems, int position) : base() {
this.articles = articles;
this.leftItems = leftItems;
this.position = position;
}
public override View OnCreateView (LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate (Resource.Layout.Articles, container, false);
this.articlesListView = view.FindViewById<ListView> (Resource.Id.articlesListView);
((ActionBarActivity)Activity).SupportActionBar.Title = this.leftItems[this.position - 1];
this.articlesAdapter = new ArticlesAdapter ((ActionBarActivity)this.Activity, this.articles);
this.articlesListView.Adapter = this.articlesAdapter;
return view;
}
}
最佳答案
你可以使用 http://developer.android.com/reference/android/support/v4/view/ViewPager.OnPageChangeListener.html#onPageSelected(int)在页面更改时更新 Activity 中的标题
关于c# - 获取 ViewPager fragment 中的当前索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33708506/