通过 Android 的对象内的值过滤具有 Spinner 的对象的 ListView

Filtering a ListView of objects with a Spinner by a value within the object for Android

你好,在我的项目中,我创建了一个名为 "Program" 的对象 class,其中包含许多值,例如一个数组,名为 "Category." 所有程序都显示为 ListView 并在布局中设置类别 Spinner(目的是将节目与匹配的类别进行分类)。

我有这段代码:

final ArrayAdapter spinnerAdapter =  new ArrayAdapter(getActivity(), R.layout.layout_spinner, MainActivity.categories); //MainActivity.categories is an array filled with strings

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        String text = spinner.getSelectedItem().toString();
        listAdapter.getFilter().filter(text);
        listAdapter.notifyDataSetChanged();
    }

Program.java

public class Program {

    public String programName;
    public ArrayList<String> categories;

     .....

    public ArrayList<String> getCategories () {
        return categories;
    }

    public String toString() {
        return programName;
    }
}

但这只是根据列表中的文本进行过滤,我怎样才能让它通过程序列表中的 Category 变量进行过滤?

嗯,

先看看这里,稍微了解一下过滤:

Adapter filtering android

接下来,我认为在您的情况下,您必须执行以下操作:

@Override
protected FilterResults performFiltering(CharSequence constraint) {
     FilterResults results = new FilterResults();
    // We implement here the filter logic
    if (constraint == null || constraint.length() == 0) {
        // No filter implemented we return all the list
         results.values = yourList;
         results.count = yourList.size();
    }
    else {
    // We perform filtering operation
    List<Program> finalList = new ArrayList<Program>();
    //here think of something regarding the upper and lower cases.
    for (Program p : yourList) {            
        if(p.getCategories().
              contains(constraint.toString()))
         finalList.add(p);
    }

     results.values = finalList;
     results.count =  finalList.size();
   }
   return results;
}