我刚用PagerAdapter创建了ViewPager,我把它放入了3个项目,但是当我运行程序ViewPager.ChildCount给我2个? 当我滚动到第二个视图时,适配器添加第三个项目并给我3个计数,但是当我滚动到最终视图(3)时它给我2个计数,但此时最后2个项目! 在我的代码中我试图在布局中的textView中显示位置 它在第一个卷轴中给出我的正确数字然后它随机开始混合位置 我不知道为什么?请帮助
我正在使用Xamarin 还有我的代码
public class SlidingTabsFragment : Fragment
{
private SlidingTabScrollView mSlidingTabScrollView;
private ViewPager mViewPager;
protected static View CurrentView;
protected static int CurrentViewPosition;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.Inflate(Resource.Layout.fragment_sample, container, false);
}
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
mSlidingTabScrollView = view.FindViewById<SlidingTabScrollView>(Resource.Id.sliding_tabs);
mViewPager = view.FindViewById<ViewPager>(Resource.Id.viewpager);
mViewPager.Adapter = new SamplePagerAdapter();
mViewPager.PageSelected += MViewPager_PageSelected;
mViewPager.PageScrolled += MViewPager_PageScrolled;
mSlidingTabScrollView.ViewPager = mViewPager;
}
private void MViewPager_PageScrolled(object sender, ViewPager.PageScrolledEventArgs e)
{
if (e.Position < mViewPager.ChildCount && e.Position>=0)
{
SamplePagerAdapter ad = (SamplePagerAdapter)mViewPager.Adapter;
TextView txtTitle = mViewPager.GetChildAt(e.Position).FindViewById<TextView>(Resource.Id.item_title);
int pos = ad.GetItemPosition(CurrentView);
txtTitle.Text = e.Position.ToString();
}
}
private void MViewPager_PageSelected(object sender, ViewPager.PageSelectedEventArgs e)
{
if (e.Position < mViewPager.ChildCount && e.Position >= 0)
{
SamplePagerAdapter ad = (SamplePagerAdapter)mViewPager.Adapter;
TextView txtTitle = mViewPager.GetChildAt(e.Position).FindViewById<TextView>(Resource.Id.item_title);
txtTitle.Text = e.Position.ToString();
}
}
public class SamplePagerAdapter : PagerAdapter
{
List<string> items = new List<string>();
public override void SetPrimaryItem(ViewGroup container, int position, Java.Lang.Object obj)
{
CurrentView = (View)obj;
CurrentViewPosition = position;
}
public SamplePagerAdapter() : base()
{
items.Add("Home");
items.Add("Sell");
items.Add("Rent");
}
public override int Count
{
get { return items.Count; }
}
public override bool IsViewFromObject(View view, Java.Lang.Object obj)
{
return view == obj;
}
public override Java.Lang.Object InstantiateItem(ViewGroup container, int position)
{
View view = LayoutInflater.From(container.Context).Inflate(Resource.Layout.pager_item, container, false);
container.AddView(view);
return view;
}
public string GetHeaderTitle (int position)
{
return items[position];
}
public override void DestroyItem(ViewGroup container, int position, Java.Lang.Object obj)
{
container.RemoveView((View)obj);
}
}
答案 0 :(得分:0)
我解决了,这是因为我必须设置OffScreenLimit属性