Организация поиска в listview

485
08 июня 2017, 05:55

Сделал поиск в listview по примеру, как можно убрать регистровазависимость при поиске, то есть чтобы с маленькой буквы тоже можно было искать.

String[] items;
    ArrayList<String> listItems;
    ArrayAdapter<String> adapter;
    ListView listView;
    EditText editText;
    String textPos0, textPos1,textPos3;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(layout.fragment_search, container, false);
        getActivity().setTitle(R.string.fr2);
        listView=(ListView) rootView.findViewById(id.lst);
        editText=(EditText) rootView.findViewById(id.txtsearch);
        initList();
        editText.clearFocus();
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.toString().equals("")){
                    // Обновление listview
                    initList();
                } else {
                    // выполнение поиска
                    searchItem(s.toString());
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(editText.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                FragmentTransaction tr = getFragmentManager().beginTransaction();
                String currPos = listItems.get(position);
                if (currPos.equals(textPos0)) {
                    //Создание нового фрагмента и транзакции
                    Fragment Stay1 = new Stay1();
                    // Замените все, что есть в представлении fragment_container, этим фрагментом,
                    //И добавьте транзакцию в задний стек
                    tr.replace(R.id.container, Stay1);
                    tr.addToBackStack(null);
                    //Завершить транзакцию
                    tr.commit();
                }
                    else if (currPos.equals(textPos1)) {
                    Fragment Stay2 = new Stay2();
                    tr.replace(R.id.container, Stay2);
                    tr.addToBackStack(null);
                    tr.commit();
                } else if (currPos.equals(textPos3)){
                    Fragment Stay3 = new Stay3();
                    tr.replace(R.id.container, Stay3);
                    tr.addToBackStack(null);
                    tr.commit();
                }
            }
        });
        return rootView;
    }

    public void searchItem(String textToSearch){
        for(String item:items){
            if(!item.contains(textToSearch)){
                listItems.remove(item);
            }
        }
        adapter.notifyDataSetChanged();
    }
    //передача результатов поиска в listview
    public void initList(){
        String [] arr1;
        arr1 = getResources().getStringArray(R.array.stops);
       //Arrays.sort(arr1);
        items=arr1;
        listItems=new ArrayList<>(Arrays.asList(items));
        adapter=new ArrayAdapter<String>(getActivity(), layout.list_item, id.txtitem, listItems);
        listView.setAdapter(adapter);
        textPos0 = listItems.get(0);
        textPos1 = listItems.get(1);
        textPos3 = listItems.get(9);
    }
}
Answer 1
public void searchItem(String textToSearch){
    textToSearch = textToSearch.toLowerCase();
    for(String item:items){
        if(!item.toLowerCase().contains(textToSearch)){
            listItems.remove(item);
        }
    }
    adapter.notifyDataSetChanged();
}

Попробуйте так

READ ALSO
Как изменить url swagger-а в spring?

Как изменить url swagger-а в spring?

Нужно чтобы сваггер деплоился не в рут директорию http://localhost:8080/swagger-uihtml, а в отдельную папочку api-docs

503
Проблема с выбором данных из базы данных в консоль

Проблема с выбором данных из базы данных в консоль

Не могу вытащить информацию в консоль с БД, более детальное описание вопроса в картинке ниже:

285
Could not open ServletContext resource Spring webmvc

Could not open ServletContext resource Spring webmvc

Здравствуйте, выскакивает данная ошибка, по каким причинам не понимаюПосмотрел другие ответы, мне не помогли мой web

436
Непонятная проблема с пустым стеком. The server cannot or will not process the request due to something that is perceived to be a client error

Непонятная проблема с пустым стеком. The server cannot or will not process the request due to something that is perceived to be a client error

Я разрабатываю приложение для доктораСсылка на репозиторий

852