【问题标题】:Xamarin.Android: Retrieving selected ListView element in AlertDialogXamarin.Android:在 AlertDialog 中检索选定的 ListView 元素
【发布时间】:2019-03-15 15:07:27
【问题描述】:

我正在 Xamarin.Android 中创建一个显示日期日历的日历。单击日期时,它会抓取当天的事件列表,以便在 ListView 中的自定义适配器中显示,所有这些都在 AlertDialog 中。

我想要做的是,当用户单击列表中的事件时,它会从该事件中获取信息(特别是事件网页的 URL),然后允许 @987654325 的 PositiveButton @ 以使用新的 Activity 打开该站点。

我可以轻松创建AlertDialog 并将ListView 放入其中并使用事件填充列表。我使用了代码located here,稍作修改。

我知道该事件被选择为列表视图布局文件中的android:listSelector 属性按预期触发。但是,我只是不知道如何访问单击事件或获取所选项目的位置以访问其数据。在另一个Activity 中,它只是一个ListView,我只需执行以下操作:

HistoricSitesListView.ItemClick += HistoricSitesListView_ItemClick;
void HistoricSiesListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{ code here }

这可以很好地获取该列表中各个项目的信息。但是尝试对dialogView 对象做同样的事情会给我一个View has no definition for ItemClick 错误。将 dialogView 设为 ListView 并强制转换 inflater 会产生 InvalidCast 异常。

我的修改代码如下:

    View dialogView = LayoutInflater.Inflate(Resource.Layout.EventsListLayout, null);
    AlertDialog alertDialog;
    using (var dialog = new AlertDialog.Builder(this))
    {
        dialog.SetView(dialogView);
        dialog.SetPositiveButton("More Info", (s, a) =>
        {
            if (currentEventURL != "null")
            {
                Intent eventIntent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(currentEventURL));
                StartActivity(eventIntent);
            }
        });
        dialog.SetNegativeButton("Close", (s, a) => { });
        alertDialog = dialog.Create();
    }
    var adapter = new EventModelAdapter(this, EventStringList);
    dialogView.FindViewById<ListView>(Resource.Id.eventListView).Adapter = adapter;

    dialogView.ItemClick += dialogView_ItemClick;

    void dialogView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
    {
        EventModel clickedEvent = EventStringList[e.Position];
        currentEventURL = clickedEvent.EventURL;
    };
    alertDialog.Show();

非常感谢任何和所有帮助。

【问题讨论】:

    标签: c# android listview xamarin android-alertdialog


    【解决方案1】:

    解决了。

    在 AlertDialog.Builder 中,我这样做了:

    dialog.SetView(dialogView);
    EventListView = dialogView.FindViewById<ListView>(Resource.Id.eventListView);
    

    然后在它之外,

    EventListView.Adapter = adapter;
    EventListView.ItemClick += EventListView_ItemClick;
    
    void EventListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            currentEventURL = EventStringList[e.Position].EventURL;
        }
    

    我之前尝试过,但出现空引用异常。我以为它认为适配器或项目为空,但我只需要将视图范围限定为 dialogView,因为它在日历布局中查找 eventListView,而不是 EventList 布局。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 2018-03-21
      相关资源
      最近更新 更多