android - android中自定义ArrayAdapter中的自定义getFilter

标签 android android-listview android-arrayadapter

我在自定义 arrayAdapter 中实现自定义 getFilter 时遇到问题。其实我不知道如何实现它。尝试了各种代码,但仍然没有运气。这是我的自定义数组适配器。

package com.test.FilterableList.Adapters;

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.test.FilterableList.Models.ListTO;
import com.test.FilterableList.R;

import android.widget.Filterable;


public class FilterableAdapter extends ArrayAdapter<ListTO> implements Filterable {

    // declaring our ArrayList of items
    public ArrayList<ListTO> objects;

    /* here we must override the constructor for ArrayAdapter
    * the only variable we care about now is ArrayList<Item> objects,
    * because it is the list of objects we want to display.
    */
    public FilterableAdapter(Context context, int textViewResourceId, ArrayList<ListTO> objects) {
        super(context, textViewResourceId, objects);
        this.objects = objects;
    }

    /*
     * we are overriding the getView method here - this is what defines how each
     * list item will look.
     */
    public View getView(int position, View convertView, ViewGroup parent){

        // assign the view we are converting to a local variable
        View v = convertView;

        // first check to see if the view is null. if so, we have to inflate it.
        // to inflate it basically means to render, or show, the view.
        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.list_item, null);
        }

        /*
         * Recall that the variable position is sent in as an argument to this method.
         * The variable simply refers to the position of the current object in the list. (The ArrayAdapter
         * iterates through the list we sent it)
         *
         * Therefore, i refers to the current Item object.
         */
        ListTO i = objects.get(position);

        if (i != null) {

            // This is how you obtain a reference to the TextViews.
            // These TextViews are created in the XML files we defined.

            TextView tt = (TextView) v.findViewById(R.id.list_name);
            if (tt != null){
                tt.setText(i.FileName);
            }



        }

        // the view must be returned to our activity
        return v;

    }
}

这是 ListTO 类。

package com.test.FilterableList.Models;

public class ListTO {

    public int Id;
    public String FileName;
    public String FileUri;

    public ListTO(int id, String fileName, String fileUri) {

        Id = id;
        FileName = fileName;
        FileUri = fileUri;

    }

}

这是布局。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/blacklikenbackground"
    tools:context=".AllListActivity" >

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Search"
        android:id="@+id/inputSearch"
        />


    <ListView
        android:id="@+id/test_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

这里的搜索关键字来自“inputSearch”EditText。

这是文本更改的监听器。

 inputSearch.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                        // When user changed the Text
                      //  Toast.makeText(getActivity(), cs.toString(), Toast.LENGTH_LONG).show();
                        m_adapter.getFilter().filter(cs);
                    }

                    @Override
                    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                                  int arg3) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void afterTextChanged(Editable arg0) {
                        // TODO Auto-generated method stub
                    }
                });

谢谢。

最佳答案

您遇到了问题,主要是因为您使用的是自定义对象。如果您将 String 或 int 值传递给数组适配器,它知道如何过滤它。但是,如果您通过自定义对象默认过滤器实现,则不知道如何处理。

虽然尚不清楚您要在过滤器中执行什么操作,但我建议您按照以下步骤操作。

  1. ListTO 的正确实现,虽然它与你现在的目标无关
  2. 实现自定义过滤器
  3. 返回您的过滤器

实现自定义过滤器

您要做的第一件事是,implements Filterable 来自您的数组适配器。

其次,提供你的Filter

的实现
Filter myFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
         FilterResults filterResults = new FilterResults();   
         ArrayList<ListTO> tempList=new ArrayList<ListTO>();
         //constraint is the result from text you want to filter against. 
         //objects is your data set you will filter from
         if(constraint != null && objects!=null) {
             int length=objects.size();
             int i=0;
                while(i<length){
                    ListTO item=objects.get(i);
                    //do whatever you wanna do here
                    //adding result set output array     

                    tempList.add(item);

                    i++;
                }
                //following two lines is very important
                //as publish result can only take FilterResults objects
                filterResults.values = tempList;
                filterResults.count = tempList.size();
          }
          return filterResults;
      }

      @SuppressWarnings("unchecked")
      @Override
      protected void publishResults(CharSequence contraint, FilterResults results) {
          objects = (ArrayList<ListTO>) results.values;
          if (results.count > 0) {
           notifyDataSetChanged();
          } else {
              notifyDataSetInvalidated();
          }  
      }
     };

最后一步,

@Override
     public Filter getFilter() {
        return myFilter;
    }

关于android - android中自定义ArrayAdapter中的自定义getFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19122848/

相关文章:

Android:从 SQLite 数据库行中删除值

android - 通过网站的 webview 推送通知?

android - 自定义 View 缺少适配器工具使用的构造函数

android - 自定义 ArrayAdapter getView 未被调用——为什么不呢?

java - Android:用于编写方程的库/示例代码?

android - 工具栏和菜单上的阴影未显示在重复布局中

java - ListView 填充时出现 NullPointerException

java - Android:将简单的光标链接到 ListView

java - 如何执行调用 ListView 项目上的特定号码

Android:如何使用 ArrayAdapter 获取微调项的 ID