Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an action only to Strings.xml files in Android in IntelliJIdea Plugin development

I created a IntelliJIdea Plugin, using the actions entry in plugin.xml like

  <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>

Using this setting, my action will appear after user right-click a file. Like this: right-click popup menu

The problem is that the Convert to other languages menu shows all the time, I only want this menu show when user right-click on the string.xml file, like the Open Translation Editor(Preview) menu does. (Open Translation Editor(Preview) is a feature Android Studio introduced in version 0.8.7)

What should I do?

like image 447
Wesley Avatar asked Jan 17 '26 02:01

Wesley


1 Answers

Not sure if there is a way to do this purely in XML, so somebody else feel free to chime in if you know of way, but there is a way to do this in Java.

In your action's update method, you can set whether the action is visible or not based on the name of the file using the action's Presentation object. Here's an example based on the ConvertToNinePatchAction in Android Studio:

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
    }
}

Then in XML, your action would look like this:

<action id="AL.Convert" class="com.example.plugin.ConvertToOtherLanguages">
    <add-to-group group-id="ProjectViewPopupMenu" anchor="last" />
</action>
like image 117
Michael Celey Avatar answered Jan 19 '26 17:01

Michael Celey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!