具有自定义对象的可过滤适配器

2024-01-23

我想将自动完成文本框添加到 xamarin.android 中的列表视图(自定义对象)中。

我有一个列表视图,它是从字符串数组填充的。我想使用自定义对象填充我的列表视图。

下面的代码适用于字符串数组。任何帮助实现我的自定义对象适配器都会有所帮助。

这是代码:

主.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <EditText
        android:id="@+id/search"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:hint="Enter search query" />
    <Button
        android:id="@+id/dosearch"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Filter list" />
    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

主要活动

public class MainActivity : Activity
    {
        Button _button;
        ListView _listview;
        EditText _filterText;
        FilterableAdapter _adapter;

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

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            _button = FindViewById<Button> (Resource.Id.dosearch);
            _listview = FindViewById<ListView> (Resource.Id.list);
            _filterText = FindViewById<EditText> (Resource.Id.search);
            _adapter = new FilterableAdapter (this, Android.Resource.Layout.SimpleListItem1, GetItems());
            _listview.Adapter = _adapter;

            _button.Click += delegate {
                // filter the adapter here
                _adapter.Filter.InvokeFilter(_filterText.Text);
            };

            _filterText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => {
                // filter on text changed
                var searchTerm = _filterText.Text;
                if (String.IsNullOrEmpty(searchTerm)) {
                    _adapter.ResetSearch();
                } else {
                    _adapter.Filter.InvokeFilter(searchTerm);
                }
            };
        }

        string[] GetItems ()
        {
           string[] names = new string[] { "abc", "xyz", "yyy", "aaa" };
           return names;
        }
    }

    public class FilterableAdapter : ArrayAdapter, IFilterable
    {
        LayoutInflater inflater;
        Filter filter;
        Activity context;
        public string[] AllItems;
        public string[] MatchItems;

        public FilterableAdapter (Activity context, int txtViewResourceId, string[] items) : base(context, txtViewResourceId, items)
        {
            inflater = context.LayoutInflater;
            filter = new SuggestionsFilter(this);
            AllItems = items;
            MatchItems = items;
        }

        public override int Count {
            get {
                return MatchItems.Length;
            }
        }

        public override Java.Lang.Object GetItem (int position)
        {
            return MatchItems[position];
        }

        public override View GetView (int position, View convertView, ViewGroup parent)
        {
            View view = convertView;
            if (view == null)
                view = inflater.Inflate(Android.Resource.Layout.SimpleDropDownItem1Line, null);

            view.FindViewById<TextView>(Android.Resource.Id.Text1).Text = MatchItems[position];

            return view;
        }

        public override Filter Filter {
            get {
                return filter;
            }
        }

        public void ResetSearch() {
            MatchItems = AllItems;
            NotifyDataSetChanged ();
        }

        class SuggestionsFilter : Filter
        {
            readonly FilterableAdapter _adapter;

            public SuggestionsFilter (FilterableAdapter adapter) : base() {
                _adapter = adapter;
            }

            protected override Filter.FilterResults PerformFiltering (Java.Lang.ICharSequence constraint)
            {
                FilterResults results = new FilterResults();
                if (!String.IsNullOrEmpty (constraint.ToString ())) {
                    var searchFor = constraint.ToString ();
                    Console.WriteLine ("searchFor:" + searchFor);
                    var matchList = new List<string> ();

                    var matches = 
                        from i in _adapter.AllItems
                        where i.IndexOf (searchFor, StringComparison.InvariantCultureIgnoreCase) >= 0
                        select i;

                    foreach (var match in matches) {
                        matchList.Add (match);
                    }

                    _adapter.MatchItems = matchList.ToArray ();
                    Console.WriteLine ("resultCount:" + matchList.Count);

                    Java.Lang.Object[] matchObjects;
                    matchObjects = new Java.Lang.Object[matchList.Count];
                    for (int i = 0; i < matchList.Count; i++) {
                        matchObjects [i] = new Java.Lang.String (matchList [i]);
                    }

                    results.Values = matchObjects;
                    results.Count = matchList.Count;
                } else {
                    _adapter.ResetSearch ();
                }
                return results;
            }

            protected override void PublishResults (Java.Lang.ICharSequence constraint, Filter.FilterResults results)
            {
                _adapter.NotifyDataSetChanged();
            }
        }
    }

我想要这样的 getItem 方法:

 public List<ListObject> GetItems()
 {
     List<ListObject> model = new List<ListObject>();
     model.Add(new ListObject { id = 1, Name = "abc" });
     model.Add(new ListObject { id = 1, Name = "bcd" });
     model.Add(new ListObject { id = 1, Name = "def" });
     model.Add(new ListObject { id = 1, Name = "fgh" });
     return model;
 }

这样做的主要原因是我希望根据 edittext 中输入的数据来过滤我的列表。然后取出选择的Id并进行剩余的计算。


具有自定义对象的可过滤适配器

我写一个demo https://github.com/aixiaozi/Xamarin.Android.Views/tree/master/RecyclerViewSearch关于如何搜索RecyclerView,在我的演示中我填充了我的RecyclerView with List<Chemical>。更详细的信息,你可以阅读我的回答:通过 RecyclerView 搜索 https://stackoverflow.com/questions/44998483/searching-through-recyclerview-xamarin-droid/45011379#45011379

My Chemical class :

public class Chemical
{
    public string Name { get; set; }
    public int DrawableId { get; set; }
}

当填充RecyclerView :

var chemicals = new List<Chemical>
{
    new Chemical {Name = "Manganosulfate", DrawableId = Resource.Drawable.Icon},
    new Chemical {Name = "Natriummolybdate", DrawableId = Resource.Drawable.Icon},
    new Chemical {Name = "Ergocalciferol", DrawableId = Resource.Drawable.Icon},
    new Chemical {Name = "Cyanocobalamin", DrawableId = Resource.Drawable.Icon},
};

_adapter = new RecyclerViewAdapter(this,chemicals);

EDIT :

既然你正在使用ListView,你可以参考Cheesebaron 的 SearchView-示例 https://github.com/Cheesebaron/SearchView-Sample,我想这就是你想要的。

不要忘记添加对象扩展 https://github.com/Cheesebaron/SearchView-Sample/blob/master/SearchViewSample/ObjectExtensions.cs你的项目中的类。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有自定义对象的可过滤适配器 的相关文章

随机推荐

  • C++ 中的异步线程安全日志记录(无互斥体)

    我实际上正在寻找一种在我的 C 中进行异步和线程安全日志记录的方法 我已经探索过 log4cpp log4cxx Boost log 或 rlog 等线程安全日志记录解决方案 但似乎它们都使用互斥锁 据我所知 互斥体是一种同步解决方案 这意
  • 如何在android中将位图转换为PDF格式[关闭]

    Closed 这个问题需要细节或清晰度 help closed questions 目前不接受答案 我在 thepic 变量中有位图 它是位图类型 imageUri Uri intent getParcelableExtra Intent
  • C++11 类型推断期间控制优先级的规则是什么?

    管理 float double 类型的 C 11 类型推断的优先级规则是什么 例如 当从包含多种类型的表达式进行推断时 如下所示 auto var float 1 double 1 结果将是double 这就是所谓的floating poi
  • 如何在 Matplotlib 中反转轴并设置极坐标图的零位置?

    使用 Matplotlib 极坐标图时 theta 轴默认零位置为 或 右侧 角度逆时针增大 如下所示这个例子 https matplotlib org examples pylab examples polar demo html 如何指
  • C++0x 闭包的未定义行为:II

    我发现 C 0x 闭包的使用令人困惑 我的初始report https stackoverflow com questions 5543169 how to make a vector of functors lambdas or clos
  • Git合并后挂钩,如何获取合并分支的名称

    我正在尝试创建合并后挂钩脚本 该脚本仅在从特定分支合并时运行 如何确定特定提交的分支更改的名称 e g if from specific branch 1 then git diff name status HEAD 1 HEAD some
  • R 包的设置数据:vegan

    我使用素食主义者从动物计数数据中确定生物多样性指标 目的是查看计数年份之间是否存在差异 即物种数量是否根据年份而减少或增加 数据以矩阵格式设置 如下所示 年是一个字符 其他都是数字 因此 R 应该省略 NA 我设置了如上所示的数据 但大多数
  • 使用 ffmpeg 循环更改 bash 变量

    我编写了一个脚本 用于根据我在时间戳上录制的视频快速创建简短的预览剪辑 我发现这些视频值得稍后查看以进行剪辑 我的带有时间戳的文件是这样写的 FILE NAME1 MM SS MM SS FILE NAME2 MM SS MM SS MM
  • 如何为 AWS Elastic Beanstalk 部署运行 npm 脚本?

    My package json has scripts start node modules bin coffee server coffee test NODE ENV test node test runner js coverage
  • Android 7.1 写入文本文件

    来自果冻豆的牛轧糖新手尝试将文本文件写入 SD 卡我知道我现在必须请求权限 但找不到任何有效的代码 尝试了以下方法 StringBuilder bodyStr new StringBuilder bodyStr append data1St
  • 用 Java 下载的 PDF 已损坏?

    我读过有关的精彩讨论如何使用 Java 从 Internet 下载并保存文件 https stackoverflow com questions 921262 how to download and save a file from int
  • 有条件地启用 C++ 类中的构造函数 [重复]

    这个问题在这里已经有答案了 我正在学习如何使用std enable if到目前为止 我在课堂上有条件地启用和禁用方法方面取得了一定程度的成功 我根据布尔值对方法进行模板化 此类方法的返回类型是std enable if这样的布尔值 这里的最
  • 如何在 Python 中创建迭代器管道?

    是否有库或推荐的方法在 Python 中创建迭代器管道 例如 gt gt gt all items get created by location surrounding cities 我还希望能够访问迭代器中对象的属性 在上面的例子中 a
  • 每个类元素的简单 jquery .hover() 方法

    没做过太多jquery 遇到了问题 我想为所有具有 social tile 类的 div 绑定悬停事件 我这样做 function var social default social tile css margin right social
  • 在 VS 2012 中调试 javascript - 本地主机缓存有旧代码

    我开始构建一个 PhoneGap 应用程序 并决定使用 VS2012 作为编辑器 调试器 因为 Eclipse 和 XCode 不进行 javascript 调试 或者它们做 也许我错过了一些东西 并且 VS2012 有 js 的智能感知
  • 对 Lisp 引用感到困惑

    我有一个关于 lisp 中列表评估的问题 Why is a and a 1 未评价 defun test a a 1 就像 print 4 这里不评价 if lt 1 2 print 3 print 4 but print 2 3 在这里评
  • C# 类似于 VBA 中的 List

    我想创建一个List
  • Codenameone 中使用 split 方法时出错

    我创建了一个新的 Codenameone 项目 它包含以下代码 String values one two tree String v values split Codename One 支持 Java 5 的一个子集String spli
  • 使用 jQuery 调用 Sinatra 删除路由

    我对 Sinatra 还很陌生 正在制作一个利用基本 CRUD 功能的简单待办事项应用程序 在后端 我有工作路线并测试了所有内容 我想合并一些前端功能 并决定使用 jQuery 来帮助实现这一点 我在 jQuery 中有一段当前代码 当单击
  • 具有自定义对象的可过滤适配器

    我想将自动完成文本框添加到 xamarin android 中的列表视图 自定义对象 中 我有一个列表视图 它是从字符串数组填充的 我想使用自定义对象填充我的列表视图 下面的代码适用于字符串数组 任何帮助实现我的自定义对象适配器都会有所帮助