WAQ*_*LAM 3 android listview searchview
我有一个列表,items我想根据 开始不同的活动item,当我单击它时会打开正确的活动,但是当我尝试从搜索视图栏中搜索列表项时,它会打开错误的活动。
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;
}
});
Run Code Online (Sandbox Code Playgroud)
我对编码了解不多,但任何人都可以解决我的问题..
您正在开始您的活动,position但是position在您进行搜索时会发生变化,因为列表会缩小并且positions会发生变化,以便获取与列表中指定位置相关联的数据,使用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);
}
Run Code Online (Sandbox Code Playgroud)
注意:您也可以使用switchas well 代替 longif或else-if梯子
例如你有三个字符串
item 1 position 0
item 2 position 1
item 3 position 2
Run Code Online (Sandbox Code Playgroud)
搜索第 2 项后,您的列表中有两个值接近您的搜索
item 2 position 0
item 3 position 1
Run Code Online (Sandbox Code Playgroud)
所以位置会改变所以不要使用它而是使用数据
代码
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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
559 次 |
| 最近记录: |