我目前有一个ListView
id=listview
,我填充了ArrayList
id=myarraylist
。我是这样做的:
final ListView listview = (ListView) findViewById(android.R.id.list);
myarraylist = (ArrayList<String>) getArray();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mylist);
myarraylist.add(...And then some other stuff I add...);
//This is the part I want to focus on
myarraylist.add("Reset High Scores");
adapter.notifyDataSetChanged();
listview.setAdapter(adapter);
现在,我希望Reset High Scores
中的条目ListView
可以点击,点击它后,我希望它Some Stuff
。我知道按钮你所做的就是设置一个onClickListener
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
..Some Stuff..
}
});
我的问题是,如果在Some Stuff
Reset High Scores
,我怎样才能发生ListView
修改:这就是我目前所拥有的
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@Override
String myString = (String) parent.getAdapter().getItem(position);
if(myString.equals("Clear High Scores")) {
//Stuff
}
}
});
答案 0 :(得分:1)
ListView
,就像Button
一样,可以设置点击监听器,但对于ListView
,方法的名称为setOnItemClickListener()
。但是,它不使用OnClickListener
,而是使用名为OnItemClickListener
的类,这对于使用ListView
更有利。该方法如下所示:
yourListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id)
{
// some stuff
}
}
)
现在这样做的好处是,您可以查看您所按压的位置包含的内容,因此解决问题的方式可能如下所示:
yourListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id)
{
String myString = (String) parent.getAdapter().getItem(position);
if(myString.equals("Reset High Scores"))
{
// Do what you want
}
}
});
答案 1 :(得分:0)
/**
* Creates a new instance
*/
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
super.onListItemClick(l, v, position, id);
//Do stuff
}
应该开始......安德鲁是对的。