【问题标题】:Add items to ListView on Android in Xamarin application在 Xamarin 应用程序中将项目添加到 Android 上的 ListView
【发布时间】:2015-12-10 14:21:57
【问题描述】:

我正在尝试在 Xamarin 应用程序中重新混合 the base Android advice for adding items to a ListView,但到目前为止我失败了。

在 Xamarin Studio 中,我创建了一个 Android 应用,目标是最新和最好的,以及所有默认设置。然后我在我的活动中添加了一个ListView,并给它一个ID @android:id/list。我已将活动的代码更改为:

[Activity (Label = "MyApp", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : ListActivity
{
    List<string> items;
    ArrayAdapter<string> adapter;

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        SetContentView (Resource.Layout.Main);
        items = new List<string>(new[] { "Some item" });
        adapter = new ArrayAdapter<string> (this, Android.Resource.Layout.SimpleListItem1, items);
        ListAdapter = adapter;

        FindViewById<Button> (Resource.Id.myButton).Click += HandleClick;
    }

    protected void HandleClick(object sender, EventArgs e) 
    {
        items.Add ("Another Item!");
        adapter.NotifyDataSetChanged ();
        Android.Widget.Toast.MakeText (this, "Method was called", ToastLength.Short).Show();
    }
}

我构建了应用程序并在我的 Nexus 5 设备上运行它。应用程序启动正常,我可以单击按钮,并看到调试器命中了处理程序。调试器没有显示其他问题,items.AddNotifyDataSetChanged 方法都被正确调用,Toast 出现在我的设备屏幕上。

但是,"Another Item!" 项目没有出现在我的列表中。

我确实注意到链接的问题和我的解决方案之间存在一个 差异。链接问题的代码如下:

setListAdapter(adapter);

我做了:

ListAdapter = adapter;

因为 setListAdapter 方法在我的 Xamarin 解决方案中不可用,并且我认为属性设置器也打算这样做。

长话短说:我需要做什么才能将项目动态添加到我的 ListView?

【问题讨论】:

    标签: c# android android-listview xamarin listactivity


    【解决方案1】:

    您正在列表中添加项目,但适配器不知道该列表。您应该做的是将项目添加到适配器:

    adapter.Add ("Another Item!");
    

    【讨论】:

    • 优秀。效果很好,解决了我的直接问题。您不会碰巧了解为什么 Xamarin 允许您直接将项目添加到适配器,而不是需要支持 ArrayList 的链接 Java 解决方案?
    • @Jeroen:您也可以直接在 Java 中向 ArrayAdapter 添加和项目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多