private AutoCompleteUserAdapter userAdapter;
private AutoCompleteTextView actvName;
private ArrayList<SearchUserItem> arrayList;
actvName = findViewById(R.id.actvName);
actvName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
actvName.setText(userAdapter.getItemNameAtPosition(position));
actvName.setSelection(actvName.getText().toString().trim().length());
}
});
actvName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
if (actvName.isPerformingCompletion()) {
} else {
if (s.toString().toLowerCase().trim().length() >= 2) {
getUserList(s.toString().toLowerCase().trim());
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
private void getUserList(String searchText) {
arrayList = new ArrayList<>();
arrayList.addAll(YOUR_LIST);
userAdapter = new AutoCompleteUserAdapter(context, R.layout.row_user, arrayList);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
actvName.setAdapter(userAdapter);
userAdapter.notifyDataSetChanged();
actvName.showDropDown();
}
});
}
AutoCompleteUserAdapter
public class AutoCompleteUserAdapter extends ArrayAdapter<SearchUserItem> {
private Context context;
private int layoutResourceId;
private ArrayList<SearchUserItem> arrayList;
public AutoCompleteUserAdapter(Context context, int layoutResourceId, ArrayList<SearchUserItem> arrayList) {
super(context, layoutResourceId, arrayList);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.arrayList = arrayList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(layoutResourceId, parent, false);
}
SearchUserItem model = arrayList.get(position);
AppCompatTextView tvUserName = convertView.findViewById(R.id.tvUserName);
tvUserName.setText(model.getFullname());
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
public String getItemNameAtPosition(int position) {
return arrayList.get(position).getName();
}
public String getItemIDAtPosition(int position) {
return arrayList.get(position).getId();
}
}