如何刷新ListView中的项目数

本文关键字:ListView 项目数 刷新 何刷新 | 更新日期: 2023-09-27 18:15:38

我正在尝试Xamarin (Android)和Visual Studio 2015,我想显示加载到ListView中的项目列表(字符串)。

我希望允许用户过滤项目并显示剩余的数量。用户每次输入一个字母,数字就会被刷新。当前数字改变了,但值不是匹配最后一个条目,而是匹配之前的一个条目。

请查看下面的代码片段:

public class MainActivity : Activity
{
    private static readonly List<string> fullData = new List<string>();
    private ListView _dList;
    private EditText _filterText;
    private TextView _numberOfItems;
    private ArrayAdapter<string> _adapter;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        var sr = new StreamReader(Assets.Open("dictionary.txt", Access.Streaming));
        fullData.AddRange(sr.ReadToEnd().Split(new[] { System.Environment.NewLine }, StringSplitOptions.None));
        _adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, fullData);
        _dList = FindViewById<ListView>(Resource.Id.dictionaryList);
        _dList.Adapter = _adapter;
        _filterText = FindViewById<EditText>(Resource.Id.filterText);
        _filterText.TextChanged += FilterOnTextChanged;
        _numberOfItems = FindViewById<TextView>(Resource.Id.numberOfItems);
        _numberOfItems.Enabled = false;
        _numberOfItems.Text = string.Format("No. matched: {0}", _dList.Count);
    }
    private void FilterOnTextChanged(object sender, TextChangedEventArgs args)
    {
        _adapter.Filter.InvokeFilter(_filterText.Text);
        _numberOfItems.Text = string.Format("No. matched: {0}", _dList.Count);
    }
}

问候,jbk

如何刷新ListView中的项目数

调用_adapter.NotifyDataSetChanged()触发刷新:

    _adapter.Filter.InvokeFilter(_filterText.Text);
    _numberOfItems.Text = string.Format("No. matched: {0}", _dList.Count);
    // Notify any dependent views that the underlying data has changed
    _adapter.NotifyDataSetChanged();

参见BaseAdapter - NotifyDataSetChanged文档