You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中ListView的onItemClick与onItemLongClick无响应问题

解决ListView点击/长按事件无响应问题

嘿,看了你的代码,马上发现了核心问题——你虽然让Fragment实现了OnItemClickListener和OnItemLongClickListener接口,但从来没把这些监听器绑定到你的ListView上!这就好比你给按钮写了点击逻辑,但忘了告诉按钮“点击的时候要执行这个逻辑”,自然不会有响应啦。

下面一步步给你修正问题:

1. 给ListView绑定点击/长按监听器

在GetRecordsTask的onPostExecute方法里,设置完Adapter之后,立刻添加监听器绑定:

@Override
protected void onPostExecute(ArrayList<Records> empList) {
    if (activityWeakRef.get() != null && !activityWeakRef.get().isFinishing()) {
        records = empList;
        if (empList != null) {
            if (empList.size() != 0) {
                recordsListAdapter = new RecordsListAdapter(activity, empList);
                recordsListView.setAdapter(recordsListAdapter);
                // 新增这两行,绑定监听器到当前Fragment
                recordsListView.setOnItemClickListener(RecordsListFragment.this);
                recordsListView.setOnItemLongClickListener(RecordsListFragment.this);
            } else {
                Toast.makeText(activity, "No Records about records... wait wot m8?", Toast.LENGTH_LONG).show();
            }
        }
    }
}

2. 修正onItemClick里的Bundle键错误

你在传递数据的时候,键写成了"selectedRecord,"(多了个逗号),这会导致后续DialogFragment取不到数据,顺便一起改了:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Records record = (Records) parent.getItemAtPosition(position);
    if (records != null) {
        Bundle arguments = new Bundle();
        // 去掉键里多余的逗号
        arguments.putParcelable("selectedRecord", record);
        CustomRecordsDialogFragment customRecordsDialogFragment = new CustomRecordsDialogFragment();
        customRecordsDialogFragment.setArguments(arguments);
        customRecordsDialogFragment.show(getFragmentManager(), CustomRecordsDialogFragment.ARGUMENT_ITEM_ID);
    }
}

3. 调整onResume方法的执行顺序

当前你的onResume里先设置标题再调用super.onResume(),不符合Android生命周期规范,应该先调用父类方法再做自定义操作,同时加个非空判断避免空指针:

@Override
public void onResume() {
    super.onResume(); // 先执行父类的生命周期方法
    getActivity().setTitle(R.string.app_name);
    if (getActivity().getActionBar() != null) {
        getActivity().getActionBar().setTitle(R.string.app_name);
    }
}

额外优化建议

  • 在onDestroyView里取消AsyncTask,避免内存泄漏:
@Override
public void onDestroyView() {
    super.onDestroyView();
    if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
        task.cancel(true);
    }
}
  • 确保Records类正确实现了Parcelable接口,否则putParcelable传递数据会失败。

做完这些修改后,你的ListView点击和长按事件应该就能正常响应了!

内容的提问来源于stack exchange,提问作者Pero Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:00:33