Android为列表视图创建监听器onLongClick

时间:2015-02-16 09:22:20

标签: android android-listview

在我的应用程序中,我有一个带有一些片段的活动。其中一个片段我有列表视图和我想创建监听器来监听onLong点击活动中的Listview项目,例如,如果最终用户长按listview项目到片段我必须显示Toast in活性

对于此操作,我创建了接口侦听器,例如:

public interface IOnLongClickReceiveSmsMaster {

    public void onLogin(Integer position);
}

在活动i中创建BroadcastReceiver为:

方法:

IntentFilter filter = new IntentFilter(M.ACTION_BROADCAST_LONGCLICK_LISTVIEW);
registerReceiver(NotifyLongClickOnItems, filter);

广播功能:

   private final BroadcastReceiver NotifyLongClickOnItems = new BroadcastReceiver() {
   @Override
   public void onReceive(Context ctxt, Intent i) {
        Toast.makeText(MainView.this, "LongClick", Toast.LENGTH_SHORT).show();
      }

现在进入Fragment我必须设置定义到LongClick的接口:

    private static IOnLongClickReceiveSmsMaster mOnLongClickReceiveSmsMaster;
    public View onCreateView( ... ){
    listview= (ListView) view.findViewById(R.id.listView);
    listview.setOnLongListener(new IOnLongClickReceiveSmsMaster() {

        @Override
        public void onLogin(Integer position) {


        }

    });
   };
   .
   .
   .
   }

public static void setOnLongListener(IOnLongClickReceiveSmsMaster l) {
    mOnLongClickReceiveSmsMaster = l;
}

不幸的是我的代码不正确,我收到了这个错误:

The method setOnLongListener(new IOnLongClickReceiveSmsMaster(){}) is undefined for the type ListView

我认为我的分析有这种能力是不正确的,请帮我解决这个问题

2 个答案:

答案 0 :(得分:1)

如果您只使用AdapterView.OnItemLongClickListener,那将会容易得多。这是如何:

getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
    public boolean onItemLongClick(    AdapterView<?> arg0,    View v,    int position,    long id){
        /* Do whatever you want here, e.g. go to next Activity etc. */
        return false;
    }
};

要通知您的Activity,请在Fragment班级

中创建一个界面
public interface LongClickNotifier{
    public void notifyOnLongClick(int position, View v);
}

Activity实现此界面

public class MainActivity extends Activity implements LongClickNotifier{

    ...
    ...

     @Override
     public void notifyOnLongClick(int position, View v){

         /* Do whatever you want here with "position" and "v". */
     }
}

现在在Fragment

getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
    public boolean onItemLongClick(    AdapterView<?> arg0,    View v,    int position,    long id){
        ((LongClickNotifier)getActivity()).notifyOnLongClick(position, v);
        return false;
    }
};

你去吧!无需创建BroadcastReceiver或其他任何内容!

答案 1 :(得分:0)

首先,您只需使用列表视图对象。

ListView listView = (ListView)findViewById(R.id.yout_list_view_layout_id_here);

之后,只需定义一个列表视图的监听器。

 listView.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int pos, long id) {
            Log.v("List view long clicked ","position : " + pos);
            return true;
        }
    });