Android
AutoCompleteTextView
Recherche…
Remarques
Si vous souhaitez proposer des suggestions à l'utilisateur lorsqu'il saisit un champ de texte modifiable, vous pouvez utiliser un AutoCompleteTextView
. Il fournit des suggestions automatiquement lorsque l'utilisateur tape. La liste des suggestions est affichée dans un menu déroulant à partir duquel l'utilisateur peut en sélectionner un pour remplacer le contenu de la zone d'édition.
AutoCompleteTextView simple et codé en dur
Conception (XML de mise en page):
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp"
android:ems="10" />
Recherchez la vue dans le code après setContentView()
(ou son équivalent de fragment ou de vue personnalisée):
final AutoCompleteTextView myAutoCompleteTextView =
(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
Fournissez des données codées en dur via un adaptateur:
String[] countries = getResources().getStringArray(R.array.list_of_countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,countries);
myAutoCompleteTextView.setAdapter(adapter);
Astuce: Bien que la méthode préférée soit de fournir des données via un Loader
quelconque au lieu d'une liste codée comme celle-ci.
AutoComplete avec CustomAdapter, ClickListener et Filter
Mise en page principale: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<AutoCompleteTextView
android:id="@+id/auto_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="2"
android:hint="@string/hint_enter_name" />
</LinearLayout>
Disposition des lignes row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/lbl_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="16dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
strings.xml
<resources>
<string name="hint_enter_name">Enter Name</string>
</resources>
MainActivity.java
public class MainActivity extends AppCompatActivity {
AutoCompleteTextView txtSearch;
List<People> mList;
PeopleAdapter adapter;
private People selectedPerson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = retrievePeople();
txtSearch = (AutoCompleteTextView) findViewById(R.id.auto_name);
adapter = new PeopleAdapter(this, R.layout.activity_main, R.id.lbl_name, mList);
txtSearch.setAdapter(adapter);
txtSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
//this is the way to find selected object/item
selectedPerson = (People) adapterView.getItemAtPosition(pos);
}
});
}
private List<People> retrievePeople() {
List<People> list = new ArrayList<People>();
list.add(new People("James", "Bond", 1));
list.add(new People("Jason", "Bourne", 2));
list.add(new People("Ethan", "Hunt", 3));
list.add(new People("Sherlock", "Holmes", 4));
list.add(new People("David", "Beckham", 5));
list.add(new People("Bryan", "Adams", 6));
list.add(new People("Arjen", "Robben", 7));
list.add(new People("Van", "Persie", 8));
list.add(new People("Zinedine", "Zidane", 9));
list.add(new People("Luis", "Figo", 10));
list.add(new People("John", "Watson", 11));
return list;
}
}
Classe de modèle: People.java
public class People {
private String name, lastName;
private int id;
public People(String name, String lastName, int id) {
this.name = name;
this.lastName = lastName;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getlastName() {
return lastName;
}
public void setlastName(String lastName) {
this.lastName = lastName;
}
}
Classe d'adaptateur: PeopleAdapter.java
public class PeopleAdapter extends ArrayAdapter<People> {
Context context;
int resource, textViewResourceId;
List<People> items, tempItems, suggestions;
public PeopleAdapter(Context context, int resource, int textViewResourceId, List<People> items) {
super(context, resource, textViewResourceId, items);
this.context = context;
this.resource = resource;
this.textViewResourceId = textViewResourceId;
this.items = items;
tempItems = new ArrayList<People>(items); // this makes the difference.
suggestions = new ArrayList<People>();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row, parent, false);
}
People people = items.get(position);
if (people != null) {
TextView lblName = (TextView) view.findViewById(R.id.lbl_name);
if (lblName != null)
lblName.setText(people.getName());
}
return view;
}
@Override
public Filter getFilter() {
return nameFilter;
}
/**
* Custom Filter implementation for custom suggestions we provide.
*/
Filter nameFilter = new Filter() {
@Override
public CharSequence convertResultToString(Object resultValue) {
String str = ((People) resultValue).getName();
return str;
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
suggestions.clear();
for (People people : tempItems) {
if (people.getName().toLowerCase().contains(constraint.toString().toLowerCase())) {
suggestions.add(people);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
List<People> filterList = (ArrayList<People>) results.values;
if (results != null && results.count > 0) {
clear();
for (People people : filterList) {
add(people);
notifyDataSetChanged();
}
}
}
};
}
Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow