问题
I want some directions. I have not much clear understanding about it. So please...
Here is my edit-text in xml form:
<EditText android:id="@+id/editTextName" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_margin="3dp" android:hint="Insert Name" android:onClick="surNameEditTextClick" />Code to get the input-string of the edit-text:
EditText nameText = (EditText) findViewById(R.id.editTextName); String name = nameText.getText().toString();Saving the name string into an array-list of string:
ArrayList<String> nameArrayList = new ArrayList<String> ; //created globally if(!(nameArrayList.contains(name))){ //Adding input string into the name array-list nameArrayList.add(name) ; }Putting this array-list into the shared-preferences:
SharedPreferences saveGlobalVariables = getSharedPreferences(APP_NAME, 0); SharedPreferences.Editor editor = saveGlobalVariables.edit(); editor.putStringSet("name", new HashSet<String>(surNameArrayList)); editor.commit();Getting all Shared-Preferences data back to array-list when program loads (in onCreate() ):
SharedPreferences loadGlobalVariables = getSharedPreferences(APP_NAME, 0); nameArrayList = new ArrayList<String>(loadGlobalVariables.getStringSet("name", new HashSet<String>()));
Now how to get this data in some view form under that edit-text. I have seen different methods but not understanding clearly. If I use the
EditText mNameEditText;
mNameEditText = (EditText)findViewById(R.id.editTextName);
mNameEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s){
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int count){
}
});
Then what code snipet will be used here? Which textView or list-view should be used and where??? I am unable to understand it. If any other method is available, then please provide here. regards,
回答1:
You are most of the way there. I recommend using an AutoCompleteTextView and simply binding your List to an ArrayAdapter. (An AutoCompleteTextView already has the dropdown feature to help the user select between similar entries and doesn't require a TextWatcher.)
Code from documentation:
public class CountriesActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.countries_list);
textView.setAdapter(adapter);
}
private static final String[] COUNTRIES = new String[] {
"Belgium", "France", "Italy", "Germany", "Spain"
};
}
(You can use your ArrayList in an identical manner to the primitive Array above.)
来源:https://stackoverflow.com/questions/14912030/getting-list-of-previously-entered-strings-under-the-edit-text-in-android-just