欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

浅谈Action条件化Enable设置的机制 博客分类: Eclipse Plug-in开发 EclipseXMLUI 

程序员文章站 2024-02-26 15:40:10
...

前面有片entry写了如何动态设置Action的Enable性,使用了plugin.xml中的enableFor机制,虽然达到了效果,但是没说清楚具体的机制,今天在这里简单说一下我的理解。

如果我们的Action是继承自org.eclipse.ui.actions.ActionDelegate这个类,我们可以发现它有一个方法叫做selectionChanged,其完整的接口如下:

<!---->1 public void selectionChanged(IAction action, ISelection selection)

让我们看一看它的java doc是怎么说的:
Notifies this action delegate that the selection in the workbench has changed.
Implementers can use this opportunity to change the availability of the action or to modify other presentation properties.
When the selection changes, the action enablement state is updated based on the criteria specified in the plugin.xml file. Then the delegate is notified of the selection change regardless of whether the enablement criteria in the plugin.xml file is met.
param action the action proxy that handles presentation portion of the action
param selection the current selection, or null if there is no selection.

好,很清楚的看到,这里是改变Action的Enable性的地方,当我们复写了这个方法之后,eclipse会调用它来判断是否Enable这个Action,即它是一个Callback。

从参数来看,action就应该是我们想要用的那个Action;那么selection是什么呢?我试验了一下,当在TextEditor中选择content的时候,这个selection是一个TextSelection。由此可以推断出,selection应该是我们在eclipse上面的各种操作的一个抽象,即每次我们做了不同的操作,这个selectionChanged都会被调用。

这样看来,我只要在selectionChanged中把selection转型成TextSelection然后获得其Text,判断这个Text是否为空并使用action的setEnable方法就可以达到我的目的了。但是,实际运行的结果是,当我不先选择实现这个selectionChanged的Action,这个函数是不会被调用的。也就是说,对Action的Enable性的设置在最开始是无效的,只有先选择了这个Action后才有效。

这样显然不行,于是还得使用enableFor这个办法。我想,也许enableFor也是使用的selectionChanged这个机制,但是会在初始化Action的时候就调用它,这样就会达到理想的结果了。

相关标签: Eclipse XML UI