在我隐藏键盘之前,在SearchView上键入时ListView不会更新

时间:2018-06-27 14:24:41

标签: c# android listview xamarin searchview

我正在创建一个连接到Azure搜索服务的Android应用。我添加了SearchView和ListView。这个想法是,当我在SearchView上键入内容时,我会从Azure搜索中获得实时结果,并将它们显示在ListView上,这是常见功能。

我的问题是,显示Android键盘时ListView不会更新。因此,最初ListView是空的,我在SearchView中键入了几个字母,但ListView上没有任何内容,但是如果我点击Android后退按钮(此时为向下按钮)以隐藏Android键盘,则将填充ListView并搜索结果出现。

如果我输入3、4个或更多字母,则只能在隐藏键盘的情况下看到正确的结果。

这基本上是我的代码:

private SearchView searchView;
private ListView listView;
private ArrayAdapter<string> adapter;

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    SetContentView(Resource.Layout.activity_main);

    searchView = FindViewById<SearchView>(Resource.Id.searchBox);
    listView = FindViewById<ListView>(Resource.Id.searchResult);

    adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1);
    listView.Adapter = adapter;

    searchView.QueryTextChange += SearchView_QueryTextChange;
}

private void SearchView_QueryTextChange(object sender, SearchView.QueryTextChangeEventArgs e)
{
    adapter.Clear();
    if (e.NewText.Length > 1)
    {
        searchTerm(e.NewText);
    }
}

private async void searchTerm(string newText)
{
    var client = new RestClient("mysearchengine.search.windows.net");
    var request = new RestRequest("indexes/myitems/docs/search", Method.POST);

    request.AddParameter("api-version", "2017-11-11", ParameterType.QueryString);
    request.AddHeader("api-key", "MYKEY");
    request.AddHeader("content-type", "application/json");
    request.RequestFormat = DataFormat.Json;
    request.AddBody(new { search = newText + "*", select = "id, title" });

    try {
        await Task.Run(() => {
        IRestResponse response = client.Execute(request);
        if (response.StatusDescription == "OK")
        {
            string values = response.Content;
            List<MyPost> myPosts = JsonConvert.DeserializeObject<List<MyPost>>(values);
            List<string> items = new List<string>();
            for(int i=0;i<myPosts.Count;i++)
            {
                items.Add(myPosts[i].Title + " (" + myPosts[i].ID + ")");
            }
            adapter.AddAll(items);
            adapter.NotifyDataSetChanged();
        }
    });
}
    catch(Exception e) { }
}

谢谢!

0 个答案:

没有答案