我有一个带有 ListView 的搜索 View 。我放了一些元素来开启一个新的 Activity 。当我在第一个 Activity 中时,好吧。但是,如果我在 Searchview 上搜索另一个项目,应用程序会服从该位置。然后,选择了错误的项目。 我怎样才能使项目点击按字符串工作?
我的代码:
public class MainActivity extends ListActivity {
ListView lv;
SearchView sv;
String[] teams={"Activity 1","Activity 2","Activity 3","Activity 4","Activity 5","Activity 6"};
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(android.R.id.list);
sv=(SearchView) findViewById(R.id.searchView);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,teams);
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String text) {
return false;
}
@Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
@Override
//to open new activity
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (position == 0) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
} else if (position == 1) {
Intent intent = new Intent(this, Main3Activity.class);
startActivity(intent);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
最佳答案
How can i make the item click work by String?
@Override
//to open new activity
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String team = teams[position];
if (team.equalsIgnoreCase("Activity 1")) {
Intent intent = new Intent(this, Activity1.class);
startActivity(intent);
} else if (team.equalsIgnoreCase("Activity 2")) {
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
} //...and so on
}
}
关于java - 如何在 Android 中通过 String 使 SearchList 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112643/