我有一個ListView
它填充在我的MainActivity中,但是當我想要找到選定的項目時,所有項目顯示具有相同的位置。ListView創建一個比需要更多的項目
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_teams);
ListView mainListView;
// Find the ListView in the UI.
mainListView = (ListView) findViewById(R.id.listView);
String values = "Team A vs Team B=Team C vs Team D";
//Matches are send in one long string, and are separated by the = sign.
//This splits the string up and puts it into an array.
String[] array = values.split("=", -1);
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.addAll(Arrays.asList(array));
ArrayAdapter listAdapter;
// Create ArrayAdapter using the planet list.
listAdapter = new ArrayAdapter<String>(this, R.layout.list_view_style, arraylist);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter(listAdapter);
}
這使得像這樣的列表:
Team A vs Team B [checkbox]
Team C vs Team D [checkbox]
我有一個按鈕,並且點擊時運行此方法:
public void matchStart(View view){
String selectedMatch = String.valueOf(((ListView) findViewById(R.id.listView)).getSelectedItemPosition());
Toast.makeText(SelectTeams.this, selectedMatch, Toast.LENGTH_SHORT).show();
}
但是每當我點擊該按鈕,無論列表視圖中的哪個項目被選中,toast都顯示相同的值。爲什麼是這樣?
你得到列表中的位置,您所需要的,請使用適配器 –