如何在IntelliJIdea插件开发中仅向Android中的Strings.xml文件添加操作

时间:2014-12-07 04:08:37

标签: android intellij-idea intellij-plugin

我使用plugin.xml中的操作条目

创建了一个IntelliJIdea插件
  <actions>
    <!-- Add your actions here -->
    <group id="AL.Localize" text="_Localize" description="Localize strings" >
      <add-to-group group-id="ProjectViewPopupMenu"/>

      <action id="AL.Convert" class="action.ConvertToOtherLanguages" text="Convert to other languages"
              description="Convert this strings.xml to other languages that can be used to localize your Android app.">

      </action>
    </group>
  </actions>

使用此设置,我的操作将在用户右键单击文件后显示。像这样: right-click popup menu

问题是Convert to other languages菜单始终显示,我只想在用户右键单击string.xml文件时显示此菜单,就像Open Translation Editor(Preview)菜单一样。 (Open Translation Editor(Preview)是Android Studio在version 0.8.7

中引入的功能

我该怎么办?

1 个答案:

答案 0 :(得分:4)

不确定是否有办法完全以XML格式执行此操作,因此如果您知道某种方式,其他人可以随意插入,但有一种方法可以在Java中执行此操作。

在您的操作的更新方法中,您可以使用操作的Presentation对象,根据文件名设置操作是否可见。以下是基于Android Studio中ConvertToNinePatchAction的示例:

package com.example.plugin;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.vfs.VirtualFile;

import org.jetbrains.annotations.Nullable;

public class ConvertToOtherLanguages extends AnAction {

    public ConvertToOtherLanguages() {
        super("Convert to other languages");
    }

    @Override
    public void update(AnActionEvent e) {
        final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
        final boolean isStringsXML = isStringsFile(file);
        e.getPresentation().setEnabled(isStringsXML);
        e.getPresentation().setVisible(isStringsXML);
    }

    @Contract("null -> false")
    private static boolean isStringsFile(@Nullable VirtualFile file) {
        return file != null && file.getName().equals("string.xml");
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        // Do your action here
    }
}

然后在XML中,您的操作将如下所示:

<action id="AL.Convert" class="com.example.plugin.ConvertToOtherLanguages">
    <add-to-group group-id="ProjectViewPopupMenu" anchor="last" />
</action>