为列表视图设置长按监听器

为列表视图设置长按监听器

本文介绍了为列表视图设置长按监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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(),但是如何?有可能吗?

I need to change this to onListItemLongClick() but how? Is it possible?

推荐答案

您的问题与,但看起来它不是完全相同的

Your question is very similar to this one, but it looks like it's not an exact duplicate.

您注意到的是 ListActivity 类确实可以没有专门针对这种情况的方法替代.

What you've noticed is that the ListActivity class does not have a method override specifically for this case.

为了将此功能添加为方法覆盖,您的类应实现AdapterView.OnItemLongClickListener接口,然后可以添加onItemLongClick()方法覆盖,其作用与已具有的onListItemClick()方法覆盖相同,但可以响应长时间的点击.

In order to add this functionality as a method override, your class should implement the AdapterView.OnItemLongClickListener interface, and then you can add the onItemLongClick() method override, which acts just as the onListItemClick() method override you already have, but responds to long clicks.

只需确保您遵循,您必须在布局xml中使用android:longClickable="true"或调用listview.setLongClickable(true);

Just make sure that you follow instructions from this answer, you must use android:longClickable="true" in the layout xml, or call 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();

    }

 //....................

这篇关于为列表视图设置长按监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 17:26