public class MainActivity extends AppCompatActivity { SearchView searchView; ListView listView; ArrayList list; ArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); searchView = findViewById(R.id.searchView); listView = findViewById(R.id.listView); list = new ArrayList<>(); list.add("Apple");//0th item list.add("Apple");//1st item list.add("Banana");//2nd item list.add("Banana");//3rd item list.add("Pineapple");//4th item list.add("Pineapple");//5th item list.add("Orange");//6th item list.add("Orange");//7th item list.add("Mango");//8th item list.add("Mango");//9th item list.add("Grapes");//10th item list.add("Grapes");//11th item list.add("Lemon");//12th item list.add("Lemon");//13th item list.add("Melon");//14th item list.add("Watermelon");//15th item list.add("Watermelon");//16th item list.add("Papaya");//17th item list.add("Papaya");//18th item adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list); listView.setAdapter(adapter); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { if(list.contains(query)) { // Toast.makeText(getApplicationContext(),query,Toast.LENGTH_SHORT).show(); adapter.getFilter().filter(query); } else { Toast.makeText(MainActivity.this, "No Match found",Toast.LENGTH_LONG).show(); } return false; } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText); //Toast.makeText(getApplicationContext(),newText,Toast.LENGTH_SHORT).show(); return false; } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int itemPosition = position; Toast.makeText(MainActivity.this,adapter.getItem(position)+ "",Toast.LENGTH_SHORT).show(); String itemValue = (String) adapter.getItem(position); Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG) .show(); } }); } }
In this program I give apple as 0th item and first item,banana as 2&3rd item and so on.. but while searching I want to show papaya as 17th or 18th based on which papaya I click .
without searching it will correctly show the number of fruits location.but while searching it will show if 4 item shown in list view it toast 0,1,2,3 based on clicking.Please help me to figure out
Advertisement
Answer
If you do a search for example using ‘P’, pineapple and papaya will be returned. Initially before search Pineapple is positions 4 and 5 and Papaya is 17th and 18th. But when you search only four results will be returned so Pineapple will be position 0, 1 and Papaya will be position 2 and 3. The position of items changes with the number of items in the list. So the behaviour you are seeing is the expected and correct one.