在列表视图中添加搜索视图

问题描述 投票:0回答:1

我制作了一个数组来传输所需的数据,该数据由3个元素(Heading,SubHeading,int ImageResourceId)组成。

数据在列表视图中显示很好,但是我无法在列表视图中进行研究。我想对特定的SubHeading或同时对这两者(Heading,SubHeading)使用searchview进行研究]

//on creat

   listView.Adapter = new HomeScreenAdapter(this, HomeScreenAdapter.tableItems);

   search.QueryTextChange += SearchV_QueryTextChange;

//filter listview

   private void SearchV_QueryTextChange(object sender, SearchView.QueryTextChangeEventArgs e)
        {


        }
//

 // 3-class listview item id
  public class TableItem
    {
        public string Heading;
        public string SubHeading;
        public int ImageResourceId;
        public TableItem(string Heading, string SubHeading, int ImageResourceId)
        {
            this.Heading = Heading;
            this.SubHeading = SubHeading;
            this.ImageResourceId = ImageResourceId;
        }
    }

}
//

//class adapter & array item

  class HomeScreenAdapter : BaseAdapter<TableItem>
        {
            public static List<TableItem> tableItems = new List<TableItem>();

            List<TableItem> items;
            Activity context;

            public void filldata()
            {

                tableItems.Add(new TableItem("hussein", "devepoer", Resource.Drawable.imaga));
                tableItems.Add(new TableItem("ahmed", "admin", Resource.Drawable.imagb));
                tableItems.Add(new TableItem("jasim", " manager", Resource.Drawable.imagc));
                tableItems.Add(new TableItem("ahmed", "admin", Resource.Drawable.imagd));
                tableItems.Add(new TableItem("jasim", " manager", Resource.Drawable.image));
                tableItems.Add(new TableItem("jasim", " manager", Resource.Drawable.imagf));

            }
        }

xamarin.android
1个回答
0
投票

根据您的代码,我通过SubHeading进行了一个示例来过滤ListView数据。

首先,创建TableItem类:

public class TableItem
{
    public string Heading { get; set; }
    public string SubHeading { get; set; }
    public int ImageResourceId { get; set; }
}

然后为ListView项创建UI:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

 <TextView android:id="@+id/textView2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<ImageView android:id="@+id/imageView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

并创建适配器并过滤数据:

 public class TableItemAdapter : BaseAdapter<TableItem>, IFilterable
{
    private List<TableItem> _originalData;
    private List<TableItem> _items;
    private readonly Activity _context;

    public TableItemAdapter(Activity activity, IEnumerable<TableItem> tableitems)
    {
        _items = tableitems.OrderBy(s => s.SubHeading).ToList();
        _context = activity;

        Filter = new TableItemFilter(this);
    }
    public override TableItem this[int position]
    {
        get { return _items[position]; }
    }

    public Filter Filter { get; private set; }

    public override int Count
    {
        get { return _items.Count; }
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var view = convertView ?? _context.LayoutInflater.Inflate(Resource.Layout.TableItem, null);

        var tableitem = _items[position];

        var HeadingView = view.FindViewById<TextView>(Resource.Id.textView1);
        var SubHeadingView = view.FindViewById<TextView>(Resource.Id.textView2);
        var imageView = view.FindViewById<ImageView>(Resource.Id.imageView1);
        HeadingView.Text = tableitem.Heading;
        SubHeadingView.Text = tableitem.SubHeading;
        imageView.SetImageResource(tableitem.ImageResourceId);

        return view;
    }

    public override void NotifyDataSetChanged()
    {
        // If you are using cool stuff like sections
        // remember to update the indices here!
        base.NotifyDataSetChanged();
    }

    private class TableItemFilter : Filter
    {
        private readonly TableItemAdapter _adapter;
        public TableItemFilter(TableItemAdapter adapter)
        {
            _adapter = adapter;
        }

        protected override FilterResults PerformFiltering(ICharSequence constraint)
        {
            var returnObj = new FilterResults();
            var results = new List<TableItem>();
            if (_adapter._originalData == null)
                _adapter._originalData = _adapter._items;

            if (constraint == null) return returnObj;

            if (_adapter._originalData != null && _adapter._originalData.Any())
            {
                // Compare constraint to all names lowercased. 
                // It they are contained they are added to results.
                results.AddRange(
                    _adapter._originalData.Where(
                        item => item.SubHeading.ToLower().Contains(constraint.ToString())));
            }

            // Nasty piece of .NET to Java wrapping, be careful with this!
            returnObj.Values = FromArray(results.Select(r => r.ToJavaObject()).ToArray());
            returnObj.Count = results.Count;

            constraint.Dispose();

            return returnObj;
        }



        protected override void PublishResults(ICharSequence constraint, FilterResults results)
        {
            using (var values = results.Values)
                _adapter._items = values.ToArray<Java.Lang.Object>().Select(r =>r.ToNetObject<TableItem>()).ToList();

            _adapter.NotifyDataSetChanged();

            // Don't do this and see GREF counts rising
            constraint.Dispose();
            results.Dispose();
        }


    }
}

实现过滤器的ObjectExtensions:

 public class JavaHolder : Java.Lang.Object
{
    public readonly object Instance;

    public JavaHolder(object instance)
    {
        Instance = instance;
    }
}

public static class ObjectExtensions
{
    public static TObject ToNetObject<TObject>(this Java.Lang.Object value)
    {
        if (value == null)
            return default(TObject);

        if (!(value is JavaHolder))
            throw new InvalidOperationException("Unable to convert to .NET object. Only Java.Lang.Object created with .ToJavaObject() can be converted.");

        TObject returnVal;
        try { returnVal = (TObject)((JavaHolder)value).Instance; }
        finally { value.Dispose(); }
        return returnVal;
    }

    public static Java.Lang.Object ToJavaObject<TObject>(this TObject value)
    {
        if (Equals(value, default(TObject)) && !typeof(TObject).IsValueType)
            return null;

        var holder = new JavaHolder(value);

        return holder;
    }
}

Mainactivity.cs:

 public class MainActivity : AppCompatActivity
{
    private SearchView searchview1;
    private ListView listview1;
    private TableItemAdapter tableitemadapter;
    private List<TableItem> tableitems;


    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.activity_main);

        searchview1 = FindViewById<SearchView>(Resource.Id.searchView1);
        listview1 = FindViewById<ListView>(Resource.Id.listView1);

        tableitems = new List<TableItem>()
        {
            new TableItem(){Heading= "hussein", SubHeading="devepoer",ImageResourceId= Resource.Drawable.plu3 },
             new TableItem(){Heading= "ahmed", SubHeading="admin",ImageResourceId= Resource.Drawable.plu3 },
              new TableItem(){Heading= "jasim", SubHeading="manager",ImageResourceId= Resource.Drawable.plu3 },
               new TableItem(){Heading= "cherry", SubHeading="admin",ImageResourceId= Resource.Drawable.plu3 },
                new TableItem(){Heading= "barry", SubHeading="manager",ImageResourceId= Resource.Drawable.plu3 },
               new TableItem(){Heading= "annine", SubHeading="manager",ImageResourceId= Resource.Drawable.plu3 }

        };
        tableitemadapter = new TableItemAdapter(this,tableitems);
        listview1.Adapter = tableitemadapter;

        searchview1.QueryTextChange += Searchview1_QueryTextChange;         

    }

    private void Searchview1_QueryTextChange(object sender, SearchView.QueryTextChangeEventArgs e)
    {
        tableitemadapter.Filter.InvokeFilter(e.NewText);        
    }

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

github中的示例:

https://github.com/CherryBu/Searchviewsample

截图:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.