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()) {
// An item has been selected from the list. Ignore.
} else {
if (s.toString().toLowerCase().trim().length() >= 2) {
getUserList(s.toString().toLowerCase().trim());
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
private void getUserList(String searchText) {
//Add data to your list after success of API call
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();
}
});
}
自动完成用户适配器
/**
* Created by Ketan Ramani on 11/07/2019.
*/
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();
}
}