为listview设置长时间点击侦听器

我有以下代码:

public class MainActivity extends ListActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } protected void onListItemClick(ListView l, View v, final int position, long id) { super.onListItemClick(l, v, position, id); }} 

我需要改变这onListItemLongClick(),但如何? 可能吗?

Solutions Collecting From Web of "为listview设置长时间点击侦听器"

你的问题与这个问题非常相似,但看起来不是一个确切的重复。

你已经注意到了, ListActivity类没有专门为这种情况覆盖的方法。

为了添加这个function作为一个方法覆盖,你的类应该实现AdapterView.OnItemLongClickListener接口,然后你可以添加onItemLongClick()方法覆盖,就像onListItemClick()方法覆盖你已经有,但响应长时间点击。

只要确保你遵循这个答案的指示,你必须在layout xml中使用android:longClickable="true" ,或者调用listview.setLongClickable(true);

例:

 public class MainActivity extends ListActivity implements AdapterView.OnItemLongClickListener { ListView listview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listview = (ListView) findViewById(R.id.list); listview.setLongClickable(true); } @Override public boolean onItemLongClick(AdapterView<?> l, View v, final int position, long id) { Toast.makeText(this, "long clicked pos: " + position, Toast.LENGTH_LONG).show(); return true; } protected void onListItemClick(ListView l, View v, final int position, long id) { super.onListItemClick(l, v, position, id); Toast.makeText(this, "short clicked pos: " + position, Toast.LENGTH_LONG).show(); } //.................... 

你可以简单地用setOnItemLongClickListener

 listview.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Toast.makeText(ClassName.class, "Long Clicked Trigger: ", Toast.LENGTH_LONG).show(); return true; } }); 

尝试这个

 listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> arg0, View v, int index, long arg3) { // write your code return false; }}); 

你可以实现这个监听器,那么这个callback函数将在你的类中作为一个函数(方法)出现:

 public class MainActivity extends ListActivity implements View.OnLongClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View listView = findViewById(R.id.list_view); listView.setOnLongClickListener(this); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); } @Override public boolean onLongClick(View v) { // Do your work here return false; } } 

是的,这是可能的,很容易实现,你只需要使列表视图的实例

 ListView lv = (ListView)findViewById(R.id.listview); lv.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View return true; } });) 

在你的情况下,而不是扩展ListActivity,你可以在XML中创build一个列表视图,并在MainActivity中查找视图,并按照上述步骤。