Your experience on this site will be improved by allowing cookies
The TextView class has a subclass named Android EditText which is used for entering and modifying text. The input type must be defined in the inputType property of EditText while using EditText width. It thus configures the keyboard according to the input. To watch the changes made over EditText, the TextWatcher interface is used by the EditText, for which the addTextChangedListener() method is called by the EditText.
Methods of TextWatcher:
In the below example, we are demonstrating the implementation of the EditText with TextWatcher to search data from ListView.
activity_main.xml:
In the activity_main.xml file, we will add the EditText and ListView.
List_item.xml:
To include the data of the ListView, the list_item.xml file is created in the layout folder.
Activity class:(File: MainActivity.java)
package com.example.radioapp; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private ListView lv; private EditText editText; private ArrayAdapter adapter; private String products[] = {"A1", "B2","C3", "D4", "E5", "F6", "G7", "H8","I9", "J10"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.listView); editText = (EditText) findViewById(R.id.editText); adapter = new ArrayAdapter(this, R.layout.list_item, R.id.product_name, products); lv.setAdapter(adapter); editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { adapter.getFilter().filter(cs); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { Toast.makeText(getApplicationContext(),"before text change",Toast.LENGTH_LONG).show(); } @Override public void afterTextChanged(Editable arg0) { Toast.makeText(getApplicationContext(),"Text changed",Toast.LENGTH_LONG).show(); } }); } } |
0 comments