Подтвердить что ты не робот

Создание текстового фильтра (например, быстрый поиск) для Spinner в Android

Я разрабатываю приложение для Android. У меня есть моя деятельность здесь с некоторыми виджетами, включая Spinner. Я хочу, чтобы объект Spinner был доступен для поиска с помощью кнопки быстрого поиска. Идея состоит в том, что пользователь постучал по объекту Spinner, и он видит список (адаптер). Если он нажимает кнопку быстрого поиска, ему должно быть предоставлено текстовое поле для ввода буквы, а затем список прядильщиков переходит к первому слову, который он находит с прилагаемой буквой. Так же, как он работает с html и выделяет теги.

Я попробовал google (и SO конечно), но кажется, что

  • никто не интересуется решением вроде этого или
  • это тщательно охраняемая тайна.:)

У вас есть некоторые указатели в этом разделе?

4b9b3361

Ответ 1

Похоже, вы говорите о аналогичной функциональности, приведенной в AutoCompleteTextView

Ответ 2

Я знаю, что этот вопрос старый, но сегодня мне также нужна эта функция, и потому, что я не смог ничего найти, я сделал себе адаптер для этих spinner

Адаптер:

public class Searchspinner extends ArrayAdapter<String> {
    private LayoutInflater inflater;
    private boolean dropdown = false;
    private OnClickListener onsearch;
    private ActionBar ab;
    private final ArrayList<String> result = new ArrayList<String>();
    private InputMethodManager keyboard;
    private boolean searching = false;
    public Searchspinner(Context context, int resource,
            ArrayList<String> objects, LayoutInflater l, ActionBar a,
            InputMethodManager imm, String spinnerid) {
        super(context, resource, objects);
        inflater = l;
        ab = a;
        keyboard = imm; 
        createSearch();
        // TODO Auto-generated constructor stub
    }
    @Override
    public View getDropDownView(int position, View cnvtView, ViewGroup prnt{
        dropdown = true;
        return getCustomView(position, cnvtView, prnt);
    }
    @Override
    public View getView(int pos, View cnvtView, ViewGroup prnt) {
        dropdown = false;
        return getCustomView(pos, cnvtView, prnt);
    }
    public View getCustomView(int position, View convertView, ViewGroup     parent) {
        if (!dropdown) {
            View mySpinner = inflater.inflate(
                    R.layout.spinner_ressource_search, parent, false);
            TextView main_text = (TextView) mySpinner
                    .findViewById(R.id.tv_spinner_first);
            main_text.setText(getItem(position));
            ImageButton search = (ImageButton) mySpinner
                    .findViewById(R.id.searchbutton);
            if (!searching) {
                search.setImageResource(R.drawable.search);
            } else {
                search.setImageResource(R.drawable.search_check);
            }
            search.setOnClickListener(onsearch);
            return mySpinner;
        }
        View mySpinner = inflater.inflate(R.layout.auftragtextview, parent,
                false);
        TextView sub_text = (TextView)  mySpinner.findViewById(R.id.TextView01);
        sub_text.setText(getItem(position));
        return mySpinner;
    }
    private void createSearch() {
        onsearch = new OnClickListener() {
            @Override
            public void onClick(View v) {       
                // TODO Auto-generated method stub
                if (searching) {
                    searching = false;
                    ab.setCustomView(R.layout.actionbar_layout);
                    ab.getCustomView().setTag("0");
                    keyboard.toggleSoftInput(0,
                            InputMethodManager.HIDE_IMPLICIT_ONLY);
                    for (int i = 0; i < result.size(); i++) {
                        add(result.get(i));
                        result.remove(i);
                        i--;
                    }
                    ((ImageButton)  v).setImageResource(R.drawable.search);
                    return;
                }
                ((ImageButton)  v).setImageResouce(R.drawable.search_check);
                searching = true;
                ab.setCustomView(R.layout.searchable);
                final EditText et = (EditText) ab.getCustomView()
                        .findViewById(R.id.editText1);
                et.setActivated(true);
                    keyboard.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                        0);
                et.requestFocus();
                et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void onTextChanged(CharSequence s, int start,
                            int before, int count) {
                        for (int i = 0; i < getCount(); i++) {
                            if (!getItem(i).contains(s)) {
                                result.add(getItem(i));
                                remove(getItem(i));
                                i--;
                            }
                        }
                        for (int i = 0; i < result.size(); i++) {
                            if (result.get(i).toLowerCase()
                                        .contains(s.toString().toLowerCase())) {
                                add(result.get(i));
                                result.remove(i);
                                i--;
                            }
                        }
                    }
                    @Override
                    public void beforeTextChanged(CharSequence s,
                            int start, int count, int after) {
                        // TODO Auto-generated method stub
                    }
                    @Override
                    public void afterTextChanged(Editable s) {
                        // TODO Auto-generated method stub
                    }
                });
            }
        };
    }
}

В файле spinner_ressource_search.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TextView
    android:id="@+id/tv_spinner_first"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="TextView" />

<ImageButton
    android:id="@+id/searchbutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:background="@android:color/transparent"
    android:src="@drawable/search" />

</RelativeLayout>

и auftragtextview.xml:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/TextView01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@+d/TextView01"
    android:textSize="16sp" >
</TextView>

и вот как вы создаете адаптер:

Searchspinner auftragSpinnerAdapter = new Searchspinner(
    this.getApplicationContext(),
    R.layout.auftragtextview,
    list_auftragSpinner,getLayoutInflater(),
    getActionBar(),
    (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)
);  

Я надеюсь, что это поможет кому угодно, и что я не пропустил уже построенный способ сделать это: D
Приветствия

Edit:

Файл searcheble.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/actionbar_background_beosys" >
<EditText
    android:id="@+id/editText1"
    android:hint="@string/suche"
    android:layout_width="fill_parent"
    android:layout_height="40dp"
    android:layout_marginLeft="15dp"
    android:paddingLeft="15dp"
    android:paddingRight="15dp"
    android:layout_marginRight="15dp"
    android:singleLine="true"
  /> 

Итак, EditText1 - это просто простой editText в представлении, который попадает в панель действий при поиске.

ActionbarLayout - это обычный ActionbarView.

Ответ 3

Вы можете реализовать его сами.

Используйте кнопку вместо spinner, создайте диалог с EditText для ввода запроса и ListView для содержимого, которое вы хотите отобразить. Затем отфильтруйте содержимое ListView в соответствии с тем, что пользователь вводит в EditText.

filter(list, text);
adapter.notifyDataSetChanged();