Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

RCP 插件開發:Command 之間如何傳值

編輯:關於 Android 程式設計

在 Eclipse RCP 插件開發中,常會有這樣的需求:執行某個 command 時想一併攜帶一些資訊,並在 command 內取得這些資訊。該怎麼實作呢?答案是利用 ExecutionEvent 物件來承載資料(例如透過它攜帶的 ApplicationContext 傳遞物件,也可以傳遞 Map 等其他型別)。

一、傳值部分

先取得 ICommandService,再呼叫 command 並透過 ExecutionEvent 把要傳遞的物件帶入:

// 獲取 ICommandService
ICommandService commandService = (ICommandService) PlatformUI.getWorkbench()
    .getActiveWorkbenchWindow().getActivePage().getActivePart()
    .getSite().getService(ICommandService.class);

// 調用 Command 並傳遞對象
commandService.getCommand("CommandId")
    .executeWithChecks(new ExecutionEvent(null, Collections.EMPTY_MAP, null, sendObject));

二、取值部分

接著在與該 command 關聯的 handler 中,從 ExecutionEvent 取出傳入的資訊:

package command_test.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.dialogs.MessageDialog;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 */
public class SampleHandler extends AbstractHandler {
    public SampleHandler() {
    }

    /**
     * the command has been executed, so extract the needed information
     * from the application context.
     */
    public Object execute(ExecutionEvent event) throws ExecutionException {
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
        MessageDialog.openInformation(
            window.getShell(),
            "Command_Test",
            "Hello, Eclipse world");
        return null;
    }
}

關鍵就在 handler 的 execute 方法會收到 ExecutionEvent 參數,接著即可從中取出傳值階段放入的物件,完成 command 之間的資料傳遞。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved