【发布时间】:2015-10-30 18:38:13
【问题描述】:
我的 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 都会显示相同的值。这是为什么呢?
【问题讨论】:
-
您正在获取列表位置,对于您的需要,请使用适配器的 getView 方法