Xamarin.Android listview getPosition方法返回对象

问题描述 投票:0回答:2

我有一个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);
        };

enter image description here

android xamarin xamarin.forms xamarin.android
2个回答
0
投票

使用选定的列表视图项

        private void Handle_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {

            if (((ListView)sender).SelectedItem == null)
            {
                return;
            }
            else
            {
                var obj = (Person)e.SelectedItem;
            }
        }

0
投票

IDE在构建项目时无法在Adapter中转换对象的类型。因此,您可以手动进行显式转换。

Person person = (Person)listView.GetItemAtPosition(e.Position); 
© www.soinside.com 2019 - 2024. All rights reserved.