通过自定义listView同时选择和搜索

时间:2018-06-05 23:54:40

标签: android listview android-arrayadapter android-filterable

我是Android新手,我正在开发一个购物清单应用程序,但我遇到了一些麻烦。

现在,我已经创建了一个包含图像和名称字段的自定义listView。我还制作了一个自定义对象GroceryItem来填充listViews。

我希望用户能够从listView中选择GroceryItems,并搜索列表。这是我的listView的自定义适配器。

class CustomAdapter extends ArrayAdapter<GroceryItem> implements Filterable
{
private ArrayList<GroceryItem> mObjects;
private ArrayFilter mFilter;
private ArrayList<GroceryItem> mOriginalValues;

CustomAdapter(@NonNull Context context, int resource, @NonNull ArrayList<GroceryItem> inputValues) {
    super(context, resource, inputValues);
    mObjects = new ArrayList<>(inputValues);
}

public void setBackup(){
    mOriginalValues = new ArrayList<GroceryItem>();
    mOriginalValues.addAll(mObjects);
}

@SuppressLint("ClickableViewAccessibility")
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    // Get the data item for this position
    final GroceryItem currentGroceryItem = getItem(position);

    // Check if an existing view is being reused, otherwise inflate the view
    if (convertView == null) {
        convertView = getLayoutInflater().inflate(R.layout.custom_layout, parent, false);
    }

    // Lookup view for data population
    ImageView groceryImage = (ImageView) convertView.findViewById(R.id.groceryImage);
    TextView groceryNameText = (TextView) convertView.findViewById(R.id.groceryName);
    LinearLayout overallItem = (LinearLayout) convertView.findViewById(R.id.linearLayout);

    // Populate the data into the template view using data
    groceryImage.setImageResource(currentGroceryItem.getImageID());
    groceryNameText.setText(currentGroceryItem.getName());

    // Set onClickListener for overallItem
    overallItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            searchBar.clearFocus();

    // Changes the selection status of the GroceryItem
    currentGroceryItem.toggle();

    // Changes the colour of the background accordingly (to show selection)
            if(currentGroceryItem.isSelected()){
                v.setBackgroundColor(0xFF83B5C7);
            } else{
                v.setBackgroundColor(0xFFFFFFFF);
            }
        }
    });


    // Return the completed view to render on screen
    return convertView;
}

////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////FOR SEARCH FUNCTIONALITY////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////

public View getViewByPosition(int pos, ListView myListView) {
    final int firstListItemPosition = myListView.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + myListView.getChildCount() - 1;

    if (pos < firstListItemPosition || pos > lastListItemPosition ) {
        return getView(pos, null, myListView);
    } else {
        final int childIndex = pos - firstListItemPosition;
        return myListView.getChildAt(childIndex);
    }
}

public void fixToggling(){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {

            for(int i = 0; i < getCount(); ++i){

 // Finds view at index i in listView, which is a global variable
                View view = getViewByPosition(i, listView);

                if(getItem(i).isSelected()){
                    view.setBackgroundColor(0XFF83B5C7);
                } else{
                    view.setBackgroundColor(0xFFFFFFFF);
                }
            }
        }
    });
}


// The following function reverses the filter (sets everything to default)
public void reverseFilter(){

    //Replaces mObjects with mOriginal Values
    mObjects.clear();
    mObjects.addAll(mOriginalValues);

    //Loads mObjects (now filled with the original items) into the adapter
    this.clear();
    this.addAll(mObjects);

    fixToggling();
}

// The following function applies a filter given a query
public void applyFilter(String query) {

    if(query == null || query.length() == 0){
        reverseFilter();
    } else{

        // Creates a new array filter
        mFilter = new ArrayFilter();

        // performs the filters, and publishes the result (i.e. writes the result into
        // mObjects)
        mFilter.publishResults(query, mFilter.performFiltering(query));

        // Clears current content of the adapter
        this.clear();

        // Fills the adapter with the content of the filtered result
        this.addAll(mObjects);

        fixToggling();
    }
}


private class ArrayFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence prefix) {

        final FilterResults results = new FilterResults();

        if(mOriginalValues == null){
            mOriginalValues = new ArrayList<>(mObjects);
        }

        // If there is no input query
        if (prefix == null || prefix.length() == 0) {

            // Make a copy of mOriginalValues into the list
            final ArrayList<GroceryItem> list;
            list = new ArrayList<>(mOriginalValues);

            // Set the FilterResults value to the copy of mOriginalValues
            results.values = list;
            results.count = list.size();

        // If there is an input query (at least one character in length)
        } else {

            // Converts the query to a lowercase String
            final String prefixString = prefix.toString().toLowerCase();

            // Makes a copy of mOriginalValues into the ArrayList "values"
            final ArrayList<GroceryItem> values;
            values = new ArrayList<>(mOriginalValues);
            final int count = values.size();

            // Makes a new empty ArrayList
            final ArrayList<GroceryItem> newValues = new ArrayList<>();

            // Iterates through the number of elements in mOriginalValues
            for (int i = 0; i < count; i++) {

                // Gets the GroceryItem element at position i from mOriginalValues' copy
                final GroceryItem value = values.get(i);

                // Extracts the name of the GroceryItem element into valueText
                final String valueText = value.getName().toLowerCase();

                // First match against the whole, non-splitted value
                if (valueText.startsWith(prefixString)) {
                    newValues.add(value);
                }
                else {

                    // Splits the one String into all its constituent words
                    final String[] words = valueText.split(" ");

                    // If any of the constituent words starts with the prefix, adds them
                    for (String word : words) {
                        if (word.startsWith(prefixString)) {
                            newValues.add(value);
                            break;
                        }
                    }
                }
            }

            // Sets the FilterResult value to the newValues ArrayList. mOriginalValues is
            // preserved.
            results.values = newValues;
            results.count = newValues.size();

            // Changes mObjects from (potentially) the original items or the previously filtered
            // results to the new filtered results. Needs to be loaded into the adapter still.
            mObjects.clear();
            mObjects.addAll(newValues);
        }

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        notifyDataSetChanged();
    }
}

////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////

}

这是我遇到的问题。我现在有四种杂货:Apple,Banana,Grapes和Mango。如果我选择葡萄,一切都很好。它显示带有蓝色背景的葡萄和带有白色背景的所有其他物品。当我开始在搜索栏中输入“gr”时,一切正常。我只看到Grapes,项目显示为选中(蓝色背景)。当我输入“grm”时,一切都消失了,没有选择任何内容。但是,当我退回一个角色然后回到“gr”时,它会向我显示Grapes,但它不再被选中。

另一个类似的问题。再次从Apple,Banana,Grapes和Mango开始,如果我选择Grapes并搜索“b”,我会选择Banana。大。现在,当我选择Banana时,它会将其显示为已选中。但是,一旦我退格,我会回到完整的项目列表,只选择Grapes。

我编写了fixToggling()函数来迭代每个视图并根据需要修复背景颜色。我还做了一些调试,以了解每个groceryItem的isSelected布尔值是否被正确记录,因此应用程序不记得应该选择或未选择哪些应用程序不是问题。出于某种原因,切换只是关闭。

有人可以帮忙吗?我只想让用户同时使用搜索功能和项目选择。

1 个答案:

答案 0 :(得分:0)

试试这个适配器代码:

.btn .dropdown-content

希望有所帮助!