1

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

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

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

我怎样才能避免这种情况?

4

2 回答 2

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();
}
}
于 2012-10-19T18:09:20.773 回答
0

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

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

如果这感觉太 hacky 设置OnItemLongClickListenernull,您也可以将其设置为OnLongClickListener返回false,表示没有消耗长按。

mListView.setOnLongClickListener(new OnLongClickListener() {
  @Override
  public boolean onLongClick(View v) {
    return false;
  }
});
于 2018-04-09T21:05:34.677 回答