Xamarin android:如何从自定义列表视图中单击的项目中获取信息

时间:2017-03-18 18:43:38

标签: c# android xamarin xamarin.android

我需要点击该项目的ID以将其发送到另一个活动 请注意,我从JSON获取项目的信息 任何帮助将不胜感激! 这是我的代码>>>

班级

  public class TableItemm
    {
        public string discription;
        public string price;
        public int ImageResourceId;

        public TableItemm(string discription, string price, int ImageResourceId)
        {
            this.discription = discription;
            this.price = price;
            this.ImageResourceId = ImageResourceId;

        }


    }

适配器

    public class THomeScreenAdapter : BaseAdapter<TableItemm>
    {
        List<TableItemm> items;
        Activity context;
        public THomeScreenAdapter(Activity context, List<TableItemm> items) : base()
        {
            this.context = context;
            this.items = items;
        }
        public override long GetItemId(int position)
        {
            return position;
        }
        public override TableItemm this[int position]
        {
            get { return items[position]; }
        }
        public override int Count
        {
            get { return items.Count; }
        }
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            var item = items[position];
            View view = convertView; // re-use an existing view, if one is available
            if (view == null) // otherwise create a new one
                view = context.LayoutInflater.Inflate(Resource.Layout.item, null);
            view.FindViewById<TextView>(Resource.Id.DText1).Text = item.discription ;
            view.FindViewById<TextView>(Resource.Id.PText2).Text = item.price;
            view.FindViewById<ImageView>(Resource.Id.Image).SetImageResource(item.ImageResourceId);
            return view;
        }
    }

OnListItemClick

  public void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e )
    {
        var listView = sender as ListView;

       // note that >>> List<TableItemm> L2MLIStt;
        var t = L2MLIStt[e.Position];


        //var t2 = L2MLIStt2[e.Position];
       // var t3 = L2MLIStt3[e.Position];
        var x = e.Position ;

        Android.Widget.Toast.MakeText(this, x, Android.Widget.ToastLength.Long).Show();

        // take the item ID & show it in product page 
        var intent = new Intent(this, typeof(product));

       // intent.PutExtra("test", x);
        //StartActivity(intent);

    }

1 个答案:

答案 0 :(得分:1)

为Java.Lang.Object:

创建自定义扩展方法
internal static class ObjectTypeHelper
{
    public static T Cast<T>(this Java.Lang.Object obj) where T : class
    {
        var propertyInfo = obj.GetType().GetProperty("Instance");
        return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
    }
}

ItemClickEventArgs中,在你获得该职位后,将其投射到你的TableItemm:

var tableItem = listView.GetItemAtPosition(e.Position).Cast<TableItemm>();

现在您可以阅读所有元素的属性。

https://msdn.microsoft.com/en-us/library/bb311042.aspx