Android, Autocomplettextview, force text to be from the entry list

我的梦境 提交于 2019-12-03 18:30:31

问题


Is there a way to force the entry in an autocompletetextview to be one of the elements in the entrylist?

I've found a method called "performValidation" but im not sure what it actually does, and i havent been able to find much documentation or any examples.


回答1:


The AutoCompleteTextView has a method called setValidator() that takes an instance of the interface AutoCompleteTextView.Validator as parameter. AutoCompleteTextView.Validator contains isValid() with which you can check the value that has been entered, and you can "fix" this string by implementing fixText().

Seems this is the best you can get with AutoCompleteTextView, as the documentation for AutoCompleteTextView.Validator states the following:

"Since there is no foolproof way to prevent the user from leaving this View with an incorrect value in it, all we can do is try to fix it ourselves when this happens."

If your list of elements is not too long, you are probably better off using a Spinner.

****** Edit: ******

I wipped together a quick example of how you can use this, hope it helps!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<AutoCompleteTextView  
    android:id="@+id/input"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Focus me to validate above text"/>
</LinearLayout>

-

public class AutoCompleteTextViewActivity extends Activity {

    String[] validWords = new String[]{"", "snowboard", "bobsleigh", "slalom"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        AutoCompleteTextView view = (AutoCompleteTextView)findViewById(R.id.input);
        view.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, validWords));
        view.setValidator(new Validator());
        view.setOnFocusChangeListener(new FocusListener());
    }

    class Validator implements AutoCompleteTextView.Validator {

        @Override
        public boolean isValid(CharSequence text) {
            Log.v("Test", "Checking if valid: "+ text);
            Arrays.sort(validWords);
            if (Arrays.binarySearch(validWords, text.toString()) > 0) {
                return true;
            }

            return false;
        }

        @Override
        public CharSequence fixText(CharSequence invalidText) {
            Log.v("Test", "Returning fixed text");

            /* I'm just returning an empty string here, so the field will be blanked,
             * but you could put any kind of action here, like popping up a dialog?
             * 
             * Whatever value you return here must be in the list of valid words.
             */
            return "";
        }
    }

    class FocusListener implements View.OnFocusChangeListener {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            Log.v("Test", "Focus changed");
            if (v.getId() == R.id.input && !hasFocus) {
                Log.v("Test", "Performing validation");
                ((AutoCompleteTextView)v).performValidation();
            }
        }
    }
}



回答2:


Don't complicate yourself, here is a code snippet for AutoCompleteTextview validation:

String str = clientName.getText().toString();
ListAdapter listAdapter = clientName.getAdapter();
for(int i = 0; i < listAdapter.getCount(); i++) {
    String temp = listAdapter.getItem(i).toString();
    if(str.compareTo(temp) == 0) {
        return;
    }
}

For more info click here




回答3:


Another alternate way(comments are mentioned inline) :

AutoCompleteTextView txt_site_name  = findViewById(R.id.some_auto_text);
// Get the string array for the countries
String[] countries = getResources().getStringArray(R.array.ncr_parking_list_array);
// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, countries);
// txt_site_name  is name of the AutoComplete text view. or AutoCompleteTextView txt_site_name
txt_site_name.setAdapter(adapter);

txt_site_name.setValidator(new AutoCompleteTextView.Validator() {
     @Override
     public boolean isValid (CharSequence text){
          //some logic here returns true or false based on if the text is validated
          if(text == "This is what I want") 
              return true;
          else 
              return false;
     }

     @Override
     public CharSequence fixText (CharSequence invalidText){
          //If .isValid() returns false then the code comes here
          //do whatever way you want to fix in the users input and  return it
          return "This is what I want"
            }
        });

Reference: AutoCompleteTextView.Validator



来源:https://stackoverflow.com/questions/5033246/android-autocomplettextview-force-text-to-be-from-the-entry-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!