Tuesday, March 20, 2012

How to enabled/disabled the View action depending on the File selection in View? How to open file in eclipse using View Action?

1. To Create a new Action in Sample View toolbar, R-Click on "viewContribution" under org.eclipse.ui.viewActions extension point and select New -> action.

2. A new action will be created. Provide the value for id*, label*, icon, tooltip.
Value for menubarPath, toolbarPath should be "additions". It means, the action will be added on menubar as well as toolbar in eclipse workbench.
Value for enablesFor should be "1". Field - "enablesFor" is responsible for how many object(s) is/are selected. Depending on the number of object selection, action will be enable/disable.
Optionally, Add image icon for this action also.
The below screenshot is showing all the property of this action.

Property of "Open Item" action
NOTE: Some modification has done in other Java files like:
                CollapseAllActionDelegate.java
                SampleLabelProvider.java
                SampleView.java
Please download the latest project from below link, to get the updated code of this class.

3. Create a new class* in "samplecode.source.action" package and named it as "OpenFileViewActionDelegate" which implement "IViewActionDelegate" interface. Modify this class as below code snippet:



4. R-click on "action" and select New -> selection.


Add new "selection" under action

5. Provide the class* value as org.eclipse.core.resources.IFile
Optinally, you can provide the value in name field also.
This class is responsible for "File" type selection. If the selected object is File type, then only this action will be enabled otherwise disabled.
Optionally, you can provide other class also depending on the requirement like:
org.eclipse.core.resources.IFolder           - This is for Folder selection only.
org.eclipse.core.resources.IResource       - This is for all type of resources like File, Folder, Project etc.
org.eclipse.core.resources.IContainer     - This is for Folder  only.

6. Run the project. In the workspace, if only File item is selected then only this newly added action in Sample View toolbar is enabled, else disabled in other scenarios.

Action is enabled when File item is selected

Action is disabled when File item is selected


Attachment: To Download this project click here.

1 comment: