2011-12-28 95 views
6

什么registerForContextMenu之间的区别:差异registerForContextMenu和setOnCreateContextMenuListener?

注册一个上下文菜单中显示为给定的视图(多个视图可以显示上下文菜单)。此方法将设置视图上的View.OnCreateContextMenuListener为此活动

调用registerForContextMenu()并将它传递给View以给出上下文菜单。 当此视图接收到长按时,会显示一个上下文菜单。

和setOnCreateContextMenuListener:

注册一个回调此视图的上下文菜单中正在修建的时候被调用。 如果这种观点不是可以长时间点击的,它可以长时间点击。

哪一个要用?约长可点击的东西:两者都做同样的事情......

感谢

+0

看起来他们是一样的东西。 – 2011-12-28 03:51:27

回答

17

疑问时......看看Android的源代码!毕竟它是开源的。 :)

混帐://android.git.kernel.org/platform/frameworks/base.git/core/java/android/view/View.java:

/** 
* Register a callback to be invoked when the context menu for this view is 
* being built. If this view is not long clickable, it becomes long clickable. 
* 
* @param l The callback that will run 
* 
*/ 
public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 
    if (!isLongClickable()) { 
     setLongClickable(true); 
    } 
    mOnCreateContextMenuListener = l; 
} 

的git: //android.git.kernel.org/platform/frameworks/base.git/core/java/android/app/Activity.java:

/** 
* Registers a context menu to be shown for the given view (multiple views 
* can show the context menu). This method will set the 
* {@link OnCreateContextMenuListener} on the view to this activity, so 
* {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be 
* called when it is time to show the context menu. 
* 
* @see #unregisterForContextMenu(View) 
* @param view The view that should show a context menu. 
*/ 
public void registerForContextMenu(View view) { 
    view.setOnCreateContextMenuListener(this); 
} 

因此,答案是,它们是相同的。除了调用setOnCreateContextMenuListener()之外,registerForContextMenu()什么都不做。

+0

mmh谢谢,我从来没有试过看过任何语言的源代码,只怕几秒钟后我就会迷路,但是,下次我会看看!感谢您的回答!干杯! – Paul 2011-12-28 10:07:56

+0

答案不可能有任何问题。完美,@Trevor Johns。此外,它还显示了解决其他类似问题/疑惑的方法。 – Srichakradhar 2014-01-04 05:57:40