ListView上的setOnLongClickListener不会触发

时间:2012-05-25 10:44:04

标签: android android-layout

这段代码有什么问题?
我尝试向列表视图添加长按一下监听器,但由于某种原因无法正确启用它:

package ch.futurecom.adaptertest;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AdapterTestActivity extends ListActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        ListView lv = getListView();

        lv.setLongClickable(true);
        lv.setOnLongClickListener(new OnLongClickListener()
        {
            @Override
            public boolean onLongClick(View v)
            {
                Toast.makeText(AdapterTestActivity.this, "long clicked", Toast.LENGTH_SHORT).show();
                return true;    
            }
        });

        lv.setAdapter(new ArrayAdapter<String>(this,R.layout.row,getResources().getStringArray(R.array.items)));
    }
}

pastebin链接:
AdapterTestActivity.java - &gt; http://pastebin.com/Pw30EkEz
row.xml - &gt; http://pastebin.com/6FajncHT

谢谢!

2 个答案:

答案 0 :(得分:11)

尝试将AdapterView.OnItemLongClickListener作为

ListView lv = getListView();
            lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){ 
                   @Override 
                   public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) 
                  { 
                       Toast.makeText(AdapterTestActivity .this, "LongClicked", Toast.LENGTH_LONG).show();
                  } 
             }); 

答案 1 :(得分:3)

使用setOnItemLongClickListener代替setOnLongClickListener

lv.setOnItemLongClickListener (new OnItemLongClickListener() {
  public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
    //do your stuff here
  }
});