如何避免onItemClick和onCreateContextMenu被调用

时间:2012-10-19 16:56:58

标签: android callback android-listview android-view

我的活动使用ListView。当用户长按一个项目时我想做X,而当他正常点击时我想做Y.我的onCreate()包含如下代码:

mListView = (ListView) findViewById(android.R.id.list);
registerForContextMenu(mListView);
mListView.setOnItemClickListener(this);

我看到的行为是,当用户长按项目时,会调用onCreateContextMenu()和onItemClick()。

我该如何避免这种情况?

2 个答案:

答案 0 :(得分:0)

试试这个,我测试了它,只有长按才能调用上下文菜单,只有onclick listview点击项目事件发生

package com.example.listview;

import android.app.ListActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ListViewExampleActivity extends ListActivity {

static final String[] STATES = new String[] { "Haryana", "Punjab", "Rajasthan",
        "Maharashtra", "Madhya Pradesh", "Kerala", "Jammu","Bihar","Karnataka" , "TamilNadu",
                "Uttar Pradesh" ,"Gujrat"};
View listColor;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setListAdapter(new ArrayAdapter<String>(this, R.layout.main,STATES));

    ListView listView = getListView();
    listView.setTextFilterEnabled(true);

    listView.setBackgroundColor(getTitleColor());
    registerForContextMenu(listView);
    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            if(listColor!=null){
                listColor.setBackgroundColor(Color.BLACK);
                listColor=view;
            }else{

                listColor=view;

            }
            Log.i("called", "item click");
            listColor.setBackgroundColor(Color.BLUE);
           //on click of any item the item name will be shown in toast
            Toast.makeText(getApplicationContext(),
            ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
        }
    });

}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenuInfo menuInfo) {
    Log.i("called", "Context menu");
    Toast.makeText(getApplicationContext(),
            "Context menu", Toast.LENGTH_SHORT).show();
}
}

答案 1 :(得分:0)

为列表视图设置OnItemLongClickListenernull似乎可以解决问题,让长按处理显示上下文菜单:

mListView = (ListView) findViewById(android.R.id.list);
registerForContextMenu(mListView);
mListView.setOnItemClickListener(this);
mListView.setOnItemLongClickListener(null);

如果将OnItemLongClickListener设置为null感觉太麻烦,您也可以将其设置为返回OnLongClickListener的{​​{1}},表示长按不是消耗掉。

false