Xamarin.Android从ListView单击事件中获取对象属性

use*_*474 3 c# listview xamarin.android xamarin

我是C#(几周)和Xamarin(大约一周)的新手.

我能够从教程"在Android上的ListView中显示实体集合"(//来自http://diptimayapatra.wordpress.com/2013/07/08/xamarin-display-entity-collection-in-listview)实现ListView适配器-in-android /)

我现在的问题是我不知道如何处理TextView文本上的click事件.

我的适配器的GetView代码是:

public override  View GetView(int position, View convertView, ViewGroup parent)
{
    var incident = incidents[position];
    View view = convertView;
    if(view == null)
    {
        view = context.LayoutInflater.Inflate(
            Resource.Layout.ListViewTemplate, null);
    }

    view.FindViewById<TextView>(Resource.Id.tvIncident).Text = 
        string.Format("{0}", incident.title);

    view.FindViewById<TextView>(Resource.Id.tvIncidentDescription).Text = 
        string.Format("{0}", incident.description);

    return view;
}
Run Code Online (Sandbox Code Playgroud)

我的事件对象代码是:

public class Incident
{
   public int id {get; set;}
   public string title {get; set;}
   public string description {get; set;}
   public double latitude {get; set;}
   public double longitude {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

然后活动中的代码是

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);
    listView = FindViewById<ListView>(Resource.Id.list);

    IncidentGet incGet = new IncidentGet();
    List<Incident> incidents = incGet.GetIncidentData()

    listAdapter = new ListViewAdapter(this, incidents);
    listView.Adapter = listAdapter;

    listView.ItemClick += listView_ItemClick;
}
Run Code Online (Sandbox Code Playgroud)

然后

void listView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
    //have no idea how to get the properties of each Incident object here
}
Run Code Online (Sandbox Code Playgroud)

我不确定listView_ItemClick是否可行,或者是否有其他方式.任何建议将不胜感激

Che*_*ron 8

您订阅的事件有一些很好的参数.如果你已经探索了你得到的东西,AdapterView.ItemClickEventArgs那就会发现有一个Position属性,这基本上可以让你找到你Adapter所点击的项目View.

所以基本上你可以得到一个事件:

void listView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
    var incident = incidents[e.Position];
    // do whatever with that incident here...
}
Run Code Online (Sandbox Code Playgroud)