android listview 长按事件setOnItemLongClickListener不响应问题

时间:2022-08-14 19:36:30

我的Listview同时设置了2个监听事件 

setOnItemLongClickListener(长按事件)

和点击事件,但是点击事件我是在adapter的getView()里面设置的,

代码如下:

// 监听点击事件convertView.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {currentMusic = position;Log.i("你的选择 ","歌曲第" + currentMusic + "首 "+ musicList.get(currentMusic).getTitle());natureBinder.startPlay(currentMusic, 0);// 按钮背景设置为正在播放if (natureBinder.isPlaying()) {btnStartStop.setBackgroundResource(R.drawable.pause);}}});
这样:长按事件就无法响应啦。

解决方法是:

把Listview的点击事件写在adapter外部


点击事件代码:

lvSongs.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
currentMusic = position;
Log.i("你的选择 ",
"歌曲第" + currentMusic + "首 "
+ musicList.get(currentMusic).getTitle());
natureBinder.startPlay(currentMusic, 0);
// 按钮背景设置为正在播放
if (natureBinder.isPlaying()) {
btnStartStop.setBackgroundResource(R.drawable.pause);
}

}
});

长按事件代码:

lvSongs.setOnItemLongClickListener(new OnItemLongClickListener() {

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
final int pos = position;
Log.e("", "onItemLongClick");
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("删除该条目");
builder.setMessage("确认要删除该条目吗?");
builder.setPositiveButton("删除",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Music music =
// MusicUtils.sMusicList.remove(pos);
// mMusicListAdapter.notifyDataSetChanged();
// if (new File(music.getUri()).delete()) {
// scanSDCard();
// }
}
});
builder.setNegativeButton("取消", null);
builder.create().show();
// 有人说一定要改成true,但是flase也是可以啊
return false;

}
});

这样就都可以响应啦!具体原因我不知情,求高手指教,我是突发奇想尝试成功的。