我有一个Listview,我想把它放在点击位置。但是GetItemAtPosition方法返回Object,并且强制转换不起作用。我将其分配给“ var”类型变量,但在这种情况下,无法获得Person对象的属性和方法。我该怎么办?谢谢。
persons.Add(new Person("Random Name", "Merhaba", Resource.Drawable.image));
persons.Add(new Person("Random Name", "Merhaba", Resource.Drawable.image));
ListView listView = (ListView)FindViewById(Resource.Id.listView);
PersonAdapter adapter = new PersonAdapter(this,persons);
listView.Adapter = adapter;
listView.ItemClick += (object sender, ItemClickEventArgs e) =>
{
Person person = listView.GetItemAtPosition(e.Position); // this line gives error. (Cannot implictly convert type "Java.Lang.Object" to Person)
Toast.MakeText(this.ApplicationContext, person.Name, ToastLength.Short).Show();
var intent = new Intent(this, typeof(ChatActivity));
this.StartActivity(intent);
};
使用选定的列表视图项
private void Handle_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (((ListView)sender).SelectedItem == null)
{
return;
}
else
{
var obj = (Person)e.SelectedItem;
}
}
IDE在构建项目时无法在Adapter中转换对象的类型。因此,您可以手动进行显式转换。
Person person = (Person)listView.GetItemAtPosition(e.Position);