I have a ListView that gets data from a database. I applied the search filter on it, but it doesn't filter as I want. what I want is to filter with the first letter not middle or contains.
Here is the code:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ListView dicList;
EditText editSearch;
ArrayAdapter<String> adapterListOfWord;
ArrayList<String> mSource = new ArrayList<String>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editSearch = findViewById(R.id.edit_search);
dicList = findViewById(R.id.dic_list);
adapterListOfWord = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mSource);
dicList.setAdapter(adapterListOfWord);
editSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
// the problem is here, i want to search with the first letter not middle or contains.
adapterListOfWord.getFilter().filter(charSequence);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
I don't know how to implement and apply filterable to my project according to my codes and change the contains() to startsWith() to reach my goal.
I really appreciate your help.
Thanks in advance.
You need to use a customized adapter instead of the default one, and override the
getFilter()to filter the list with the String'sstartsWith()method:Adapter:
Usage in your code: