我有一个包含多个项目的列表视图。单击某个项目时,将打开一个“活动”。但是,当我在项目上快速点击几次时,与其相关的活动会被打开几次。如何只打开一次项目?
我使用以下代码:
private OnItemClickListener newsfeedClickHandler = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyObject newsfeed = adapter.getItem(position);
onNewsfeedClick(newsfeed);
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newsfeed, container, false);
...
listView = (ListView) view.findViewById(R.id.newsfeeds);
listView.setOnItemClickListener(newsfeedClickHandler);
listView.setAdapter(adapter);
...
return view;
}
private void onNewsfeedClick(MyObject newsfeed) {
Intent intent = createIntent(newsfeed);
startActivity(intent);
}
答案 0 :(得分:2)
阻止调用ListView项目的正确方法是(显然)禁用OnItemClickListener
:
private void onNewsfeedClick(MyObject newsfeed) {
listView.setOnItemClickListener(null);
Intent intent = createIntent(newsfeed);
startActivity(intent);
}
当此活动再次可见时,将侦听器重置为onResume
。
@Override
protected void onResume() {
super.onResume();
listView.setOnItemClickListener(newsfeedClickHandler);
}
答案 1 :(得分:1)
维护一个布尔值,说isItemClicked
并在返回列表视图时重置它。
private boolean isItemClicked;
private OnItemClickListener newsfeedClickHandler = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!isItemClicked) {
isItemClicked = true;
MyObject newsfeed = adapter.getItem(position);
onNewsfeedClick(newsfeed);
}
}
};
private void resetIsItemClicked() {
isItemClicked = false;
}
答案 2 :(得分:1)
要防止对ListView项目进行多次单击,请在listview单击侦听器中添加以下代码:
if (SystemClock.elapsedRealtime() - mLastClickTimeListViewItem < 1000){
return;
}