在Android的字符串类型listview上实现searchview
作者:互联网
我有一个项目列表,我想根据该项目启动其他活动,当我单击它时,它将打开正确的活动,但是当我尝试从搜索视图栏中搜索列表项目时,它将打开错误的活动.
listView = (ListView) findViewById(R.id.listView);
sv=(SearchView) findViewById(R.id.searchView1);
String[] values = new String[]{item1,item2,item3,item4,}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_2, android.R.id.text1, values);
listView.setAdapter(adapter);
//linking from 1 item to other activity stars with if options//
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), activity1.class);
startActivityForResult(myIntent,0);
}
if (position == 4) {
Intent myIntent = new Intent(view.getContext(), aactivity4.class);
startActivityForResult(myIntent,0);
}
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String text) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
我对编码了解不多,但是任何人都可以解决我的问题.
解决方法:
您是根据职位开始活动的,但是搜索时职位会发生变化,因为列表会缩小,职位也会发生变化,因此要获取与列表中指定位置相关联的数据,请使用getItemAtPosition
所以根据数据改变条件
if (parent.getItemAtPosition(position).equals("item1")) {
Intent myIntent = new Intent(view.getContext(), activity1.class);
startActivityForResult(myIntent,0);
}
else if (parent.getItemAtPosition(position).equals("item2")) { // use any item value here you want
Intent myIntent = new Intent(view.getContext(), aactivity4.class);
startActivityForResult(myIntent,0);
}
注意:您也可以使用switch代替长if或else-if梯子
例如,您有三个字符串
item 1 position 0
item 2 position 1
item 3 position 2
搜索完项目2后,您的列表中有两个值接近搜索范围
item 2 position 0
item 3 position 1
所以位置会改变,所以不要使用它,而是使用数据
码
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = null;
// global string to class
selectedValue = String.valueOf(parent.getItemAtPosition(position));
if (selectedValue.equals("item1")) {
// ^^^ use any item value here you want
Intent myIntent = new Intent(view.getContext(), activity1.class);
startActivityForResult(myIntent,0);
}
else if (selectedValue.equals("item2")) {
Intent myIntent = new Intent(view.getContext(), aactivity4.class);
startActivityForResult(myIntent,0);
}
}
});
标签:listview,searchview,android 来源: https://codeday.me/bug/20191026/1936063.html