我正在尝试获取Xamarin中ListView中单击项的位置,但是使用SelectedItemPosition总是返回-1。

ListView lsvSearch;
List<SearchResultItem> searchResults;

protected override void OnCreate(Bundle bundle){
    ...
    lsvSearch = FindViewById<ListView>(Resource.Id.lsvSearch);
    lsvSearch.ItemClick += LsvSearch_ItemClick;
    ...
}
private void LsvSearch_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
    ....
    Bundle valuesForActivity = new Bundle();
    valuesForActivity.PutInt("placeId", searchResults[lsvSearch.SelectedItemPosition].resultId); // lsvSearch.SelectedItemPosition always returns -1

    Intent resultIntent = new Intent(this, typeof(AboutPlace));
    ....
}


我怎么解决这个问题?如何获得点击项的位置而不是-1?

最佳答案

使用您的AdapterView.ItemClickEventArgs参数。它包含许多有用的信息,请在此处查看该类的参考:https://developer.xamarin.com/api/type/Android.Widget.AdapterView+ItemClickEventArgs/

对于您的特定问题,如果您希望所选项目的位置,请使用以下内容:e.Position

private void LsvSearch_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
    ....
    Bundle valuesForActivity = new Bundle();
    valuesForActivity.PutInt("placeId", searchResults[e.Position].resultId); // lsvSearch.SelectedItemPosition always returns -1

    Intent resultIntent = new Intent(this, typeof(AboutPlace));
    ....
}

09-26 23:48