在PagerAdapter中调用活动

时间:2016-02-25 07:01:18

标签: visual-studio-2013 xamarin android-pageradapter

我可以在PagerAdapter中调用活动吗?

点击按钮位于public override Java.Lang.Object InstantiateItem(ViewGroup container, int position)

我可以在xamarin和visulal studio 2013中做到这一点吗?

 public class SamplePagerAdapter : PagerAdapter
    {
        List<string> items = new List<string>();

        public SamplePagerAdapter() : base()
        {

            items.Add("               All Categories        ");
            items.Add("        Featured                          ");


        }

        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);


            if (position == 0)
            {
               view = LayoutInflater.From(container.Context).Inflate(Resource.Layout.pager_item, container, false);
                container.AddView(view);
                var imgcarbtn = view.FindViewById<ImageButton>(Resource.Id.imgcar);
                imgcarbtn.Click += imgcarbtn_Click;
            }
            else if (position == 1) {
                 view = LayoutInflater.From(container.Context).Inflate(Resource.Layout.featuredadds, container, false);

            }

            int pos = position + 1;

          Console.Out.WriteLine(pos);
           container.AddView(view);

            return view;
        }

        void imgcarbtn_Click(object sender, EventArgs e)
        {
            activity.StartActivity(typeof(Labas));
           //weakactivity(Labas) ;
            //throw new NotImplementedException();
        }

        private WeakReference weakactivity;
        private Activity activity
        {
            get { return weakactivity.Target as Activity; }
            set { weakactivity = new WeakReference(value); }
        }

        public SamplePagerAdapter(Activity activity)
            : base()
        {
            this.activity = activity;
        }

        public string GetHeaderTitle (int position)
        {
            return items[position];
        }

        public override void DestroyItem(ViewGroup container, int position, Java.Lang.Object obj)
        {
            container.RemoveView((View)obj);
        }
    }

1 个答案:

答案 0 :(得分:1)

是的,你可以,

在PagerAdapter的构造函数中传递Activity引用。请确保将其存储为WeakReference,以防止活动泄漏。

public class YourPagerAdapter : PagerAdapter
{
  private WeakReference weakactivity;
  private Activity activity
  {
    get { return weakactivity.Target as Activity; }
    set { weakactivity = new WeakReference(value); }
  }

  public YourPagerAdapter(Activity activity) : base()
  {
    this.activity = activity;
  }
}