2010-07-24 4 views
7

Возможно ли иметь прикрепленное к нему приложение EditTextPreference с автозаполнением?Возможно автозаполнение EditTextPreference?

Я знаю, что ho присоединяет элемент к элементу с id, но у меня возникают проблемы с тем, как присоединить ArrayAdapter к полю предпочтений.

Это неправильно, но это как можно ближе.

final String[] TEAMS = getResources().getStringArray(R.array.teams); 
AutoCompleteTextView EditTextPreference = (AutoCompleteTextView) findViewById(R.id.editTextPrefTeam);  
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, TEAMS); 
EditTextPreference.setAdapter(adapter); 

ответ

0

Возможно, если вы подкласс его и сделать свой собственный взгляд на то и использовать объект AutoCompleteTextView как элемент будет работать, так как в настоящее время я не вижу, как простой EditText может быть изменен на автозаполнения.

8

Вот обходной путь, который я реализовал, изучив исходный код EditTextPreference.java.

По существу вам необходимо подклассифицировать EditTextPreference и переопределить, когда он привязан к диалоговому окну. На этом этапе вы можете получить EditText, скопировать его значения и удалить из своей родительской группы представлений. Затем вы вводите свой Autocompletetextview и подключаете его Arrayadapter.

public class AutoCompleteEditTextPreference extends EditTextPreference 
{ 
    public AutoCompleteEditTextPreference(Context context) 
    { 
     super(context); 
    } 

    public AutoCompleteEditTextPreference(Context context, AttributeSet attrs) 
    { 
     super(context, attrs); 
    } 

    public AutoCompleteEditTextPreference(Context context, AttributeSet attrs, 
     int defStyle) 
    { 
     super(context, attrs, defStyle); 
    }  

    /** 
    * the default EditTextPreference does not make it easy to 
    * use an AutoCompleteEditTextPreference field. By overriding this method 
    * we perform surgery on it to use the type of edit field that 
    * we want. 
    */ 
    protected void onBindDialogView(View view) 
    { 
     super.onBindDialogView(view); 

     // find the current EditText object 
     final EditText editText = (EditText)view.findViewById(android.R.id.edit); 
     // copy its layout params 
     LayoutParams params = editText.getLayoutParams(); 
     ViewGroup vg = (ViewGroup)editText.getParent(); 
     String curVal = editText.getText().toString(); 
     // remove it from the existing layout hierarchy 
     vg.removeView(editText);   
     // construct a new editable autocomplete object with the appropriate params 
     // and id that the TextEditPreference is expecting 
     mACTV = new AutoCompleteTextView(getContext()); 
     mACTV.setLayoutParams(params); 
     mACTV.setId(android.R.id.edit); 
     mACTV.setText(curVal); 


     ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), 
      android.R.layout.simple_dropdown_item_1line, [LIST OF DATA HERE]); 
     mACTV.setAdapter(adapter); 

     // add the new view to the layout 
     vg.addView(mACTV); 
    } 

    /** 
    * Because the baseclass does not handle this correctly 
    * we need to query our injected AutoCompleteTextView for 
    * the value to save 
    */ 
    protected void onDialogClosed(boolean positiveResult) 
    { 
     super.onDialogClosed(positiveResult); 

     if (positiveResult && mACTV != null) 
     {   
      String value = mACTV.getText().toString(); 
      if (callChangeListener(value)) { 
       setText(value); 
      } 
     } 
    } 

    /** 
    * again we need to override methods from the base class 
    */ 
    public EditText getEditText() 
    { 
     return mACTV; 
    } 

    private AutoCompleteTextView mACTV = null; 
    private final String TAG = "AutoCompleteEditTextPreference"; 
} 
8

Мне казалось, там должен был быть «проще» путь для достижения этой цели, чем взлом класса EditTextPreference и баловаться с видом. Вот мое решение, поскольку AutoCompleteTextView расширяет EditText, мне пришлось переопределить методы EditTextPreference, которые напрямую ссылаются на их постоянный объект EditText.

public class AutoCompletePreference extends EditTextPreference { 

private static AutoCompleteTextView mEditText = null; 

public AutoCompletePreference(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    mEditText = new AutoCompleteTextView(context, attrs); 
    mEditText.setThreshold(0); 
    //The adapter of your choice 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, COUNTRIES); 
    mEditText.setAdapter(adapter); 
} 
private static final String[] COUNTRIES = new String[] { 
    "Belgium", "France", "Italy", "Germany", "Spain" 
}; 

@Override 
protected void onBindDialogView(View view) { 
    AutoCompleteTextView editText = mEditText; 
    editText.setText(getText()); 

    ViewParent oldParent = editText.getParent(); 
    if (oldParent != view) { 
     if (oldParent != null) { 
      ((ViewGroup) oldParent).removeView(editText); 
     } 
     onAddEditTextToDialogView(view, editText); 
    } 
} 

@Override 
protected void onDialogClosed(boolean positiveResult) { 
    if (positiveResult) { 
     String value = mEditText.getText().toString(); 
     if (callChangeListener(value)) { 
      setText(value); 
     } 
    } 
} 
} 

Благодаря Brady для связи с источником.

+0

Почти! Я получаю окно автозаполнения, но автоматически закрывается окно и отображается над полем ввода, при этом нижняя половина раскрывающегося списка не отображается. –

+0

На самом деле, я смог исправить свою ошибку из предыдущего комментария жестким кодированием значения для высоты выпадающего окна. –