I have a String[]
called lv_arr
, and my activity looks like this:
It contains a EditText
and below that I am displaying a above lv_arr[]
using this code:
listView = (ListView) findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,lv_arr);
listView.setAdapter(adapter);
Currently lv_arr[]
contains only one string (i.e "Notes"
), and whenever the user adds a string it will be updated. I want to add TextWatcher
on my EditText
, so I tried the following:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/addLabelText"
android:hint="Add Label">
<requestFocus/>
</EditText>
With:
addLabelText = (EditText) findViewById(R.id.addLabelText);
addLabelText.addTextChangedListener(listWatcher);
}
private final TextWatcher listWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int i, int i1, int i2) {
System.out.println(s);
}
@Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
}
};
I want a final output which, whenever user types anything in that EditText
, the significant values from my list should be displayed below it. When that EditText
is goes to a blank state, the below list should display all elements. Otherwise only matching values should be visible.
I tried using a for loop so that I can get matching values, but I am making a mistake somewhere...
So, to achieve my desired output i write code as follows:
1) i changed my EditText to SearchView
<SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/addLabelText"
/>
2)added setOnQueryTextListener on SearchView
addLabelText =(SearchView) findViewById(R.id.addLabelText);
addLabelText.setOnQueryTextListener(this);
3)implement QueryTextChangeListener 4)Then,
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
Here adapter is the adapter that i used for my List View, i.e
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,lv_arr);
listView.setAdapter(adapter);
Reference Link: http://www.tutorialsbuzz.com/2014/08/android-filters-for-simple-listview.html