Longclick问题

时间:2016-02-09 16:01:57

标签: android listview

我有以下代码,当我点击我的列表时运行,但我需要它只在我长按时弹出一个菜单,短按点做其他事情。

 @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (v.getId()==R.id.listView1) {

            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu_list, menu);
        }
    }

@Override
public boolean onContextItemSelected(MenuItem item) {


    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch(item.getItemId()) {
        case R.id.add:
            // add stuff here
            CreateWO.performClick();
            return true;
        case R.id.punchin:

            final Country country = (Country) ListView1.getItemAtPosition(getwoindex());
            punchin.performClick();
            Toast.makeText(getApplicationContext(), "Work Order="+country.code, Toast.LENGTH_SHORT).show();
            return true;
        case R.id.punchout:
            punchout.performClick();
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:1)

对于listView项目上的正常点击,请使用: listView.onItemClickListener
,对于长按,请使用: listView。 setOnItemLongClickListener 如下:

ListView lv =(ListView)findViewById(R.id.my_list); 
----
 lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Do something
            }
        });

 lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
  @Override
  public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //do something on long click
                //like show contextMenu
                return false;
            }
        });

编辑:

对于ContextMenu:
您可以在 onItemLongClick 中调用 openContextMenu(view)(如上所述) OR 您可以使用 registerForContextMenu(view)例如:

lv.setAdapter(adapter); 
registerForContextMenu(lv);

默认情况下,当用户长时间点击您的视图时,contextMenu将会打开。在这种情况下,您无需在listView上手动调用onLongClick。