简单的Android Studio 翻译插件

英语水平太差劲,这是个很无奈的事情,在android studio里面看源码,注释看不懂!怎么办呢,安装个插件吧!搜了一下,就搜到一个,还没写怎么用。自己写一个简单的吧。在网上找了一下教程,照葫芦画瓢,最后做出来了,记录一下吧。
一、先下一个IntelliJ IDEA,安装好
https://www.jetbrains.com/idea/download/

二、新建一个IntelliJ Platform Plugin 工程

ProjectSDK :  点击New,选择IntelliJ 的根目录就可以。


next ,起个名,finish。

三、新建一个Action

在src文件夹上右键->New->Action

Class Name : 生成的java文件名,Name : 在菜单中显示的名称,Groups:在那组菜单中显示,Keyboard Shortcuts :用于设置快捷键。点击OK会生成TranslationAction.java文件。


四、先显示一个MessageDialog吧

在TranslationAction.java里面添加代码:

@Override
    public void actionPerformed(AnActionEvent e) {
        // TODO: insert action logic here
        Messages.showMessageDialog(
                "试一试看看效果",
                "这是标题",
                Messages.getInformationIcon());
    }
五、运行一下

点击Run,会打开一个IntelliJ 窗口,刚才action选择了EditMenu,在Edit下可以发现一个名为translate的选项,快捷键是ALT+A。

点击一下:

六、接下来就是实现翻译功能啦

用有道API实现吧。地址:http://fanyi.youdao.com/openapi?path=data-mode

申请一个,网站名称,网站地址随便写,无所谓的东西。申请成功,会有一个 keyfrom 和 key。

七、封装数据

下面是我封装的数据格式。

package com.lcy.plugin;

import java.util.List;
import java.util.Map;

/**
 * Created by loucyin on 2016/3/25.
 */
public class Translation {
    public final static String US_PHONETIC = "us-phonetic";
    public final static String UK_PHONETIC = "uk-phonetic";
    public final static String PHONETIC = "phonetic";
    public final static String EXPLAINS = "explains";

    private final static int SUCCESS = 0;
    private final static int QUERY_STRING_TOO_LONG = 20;
    private final static int CAN_NOT_TRANSLATE = 30;
    private final static int INVALID_LANGUAGE = 40;
    private final static int INVALID_KEY = 50;
    private final static int NO_RESULT = 60;

    private String[] translation;
    private String query;
    private int errorCode;
    private Map<String, Object> basic;
    private List<Map<String, Object>> web;

    public String[] getTranslation() {
        return translation;
    }

    public void setTranslation(String[] translation) {
        this.translation = translation;
    }

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public Map<String, Object> getBasic() {
        return basic;
    }

    public void setBasic(Map<String, Object> basic) {
        this.basic = basic;
    }

    public List<Map<String, Object>> getWeb() {
        return web;
    }

    public void setWeb(List<Map<String, Object>> web) {
        this.web = web;
    }

    public String getErrorMessage() {
        switch (errorCode) {
            case SUCCESS:
                return "成功";
            case QUERY_STRING_TOO_LONG:
                return "要翻译的文本过长";
            case CAN_NOT_TRANSLATE:
                return "无法进行有效的翻译";
            case INVALID_LANGUAGE:
                return "不支持的语言类型";
            case INVALID_KEY:
                return "无效的key";
            case NO_RESULT:
                return "无词典结果";
        }
        return "这是什么鬼";
    }

    public String getPhonetic() {
        if (basic == null) {
            return null;
        }
        String phonetic = null;
        String us_phonetic = (String) basic.get(US_PHONETIC);
        String uk_phonetic = (String) basic.get(UK_PHONETIC);
        if (us_phonetic == null && uk_phonetic == null) {
            phonetic = "拼音:[" + (String) basic.get(PHONETIC) + "];";
        } else {
            if (us_phonetic != null) {
                phonetic = "美式:[" + us_phonetic + "];";
            }
            if (uk_phonetic != null) {
                if(phonetic == null)
                {
                    phonetic = "";
                }
                phonetic = phonetic + "英式:[" + uk_phonetic + "];";
            }
        }
        return phonetic;
    }

    public String getExplains() {
        if (basic == null) {
            return null;
        }
        String result = null;
        List<String> explains = (List<String>) basic.get(EXPLAINS);
        if (explains.size() > 0) {
            result = "";
        }
        for (String explain : explains) {
            result += explain + "\n";
        }
        return result;
    }

    public String getTranslationResult() {
        if (translation == null) {
            return null;
        }
        String result = null;
        if(translation.length>0) {
            result = "";
        }
        for (String r : translation) {
            result += (r + ";");
        }
        return result;
    }

    public String getWebResult() {
        if (web == null) {
            return null;
        }
        String result = null;
        if (web.size() > 0) {
            result = "";
        }
        for (Map<String, Object> map : web) {
            String key = (String) map.get("key");
            result += (key + " : ");
            List<String> value = (List<String>) map.get("value");
            for (String str : value) {
                result += (str + ",");
            }
            result += "\n";
        }
        return result;
    }

    @Override
    public String toString() {
        String string = null;
        if (errorCode != SUCCESS) {
            string = "错误代码:" + errorCode + "\n" + getErrorMessage();
        } else {
            String translation = getTranslationResult();
            if (translation != null) {
                translation = translation.substring(0, translation.length() - 1);
                if(!translation.equals(query)) {
                    string = (query + ":" + getTranslationResult() + "\n");
                }
            }
            if (getPhonetic() != null) {
                if (string == null) {
                    string = "";
                }
                string += (getPhonetic() + "\n");
            }
            if (getExplains() != null) {
                if (string == null) {
                    string = "";
                }
                string += (getExplains());
            }
            if (getWebResult() != null) {
                if (string == null) {
                    string = "";
                }
                string+="网络释义:\n";
                string += (getWebResult());
            }
        }
        if(string == null)
        {
            string = "你选的内容:"+query+"\n这是个毛线!!!\n翻译不了!";
        }
        return string;
    }
}

八、获取选中的文字

发挥自己想象力的时候到了,根据IntelliJ 的代码提示功能,试了几次竟然成功了。

@Override
    public void actionPerformed(AnActionEvent e) {

        //获取编辑器
        Editor editor = e.getData(PlatformDataKeys.EDITOR);
        if (editor != null) {
            SelectionModel model = editor.getSelectionModel();

            //获取选中的文本
            String selectedText = model.getSelectedText();

            if (selectedText != null) {
                //翻译并显示
                getTranslation(selectedText);
            }
        }
    }
九、请求网络获取翻译结果

我是用httpclient4.5实现的,下载地址:http://hc.apache.org/downloads.cgi

private void getTranslation(String query) {
        try {
            //获取URI
            URI uri = createTranslationURI(query);
            System.out.println(uri.toString());
            //配置GET请求
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000).build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setConfig(requestConfig);
            HttpClient client = HttpClients.createDefault();

            //请求网络
            HttpResponse response = client.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                //获取响应数据
                HttpEntity resEntity = response.getEntity();
                String json = EntityUtils.toString(resEntity, "UTF-8");

                //转化为Translation对象
                Gson gson = new Gson();
                Translation translation = gson.fromJson(json, Translation.class);

                //显示结果
                Messages.showMessageDialog(
                        translation.toString(),
                        "翻译结果",
                        Messages.getInformationIcon()
                );

            } else {
                //显示错误代码和错误信息
                Messages.showMessageDialog(
                        response.getStatusLine().getReasonPhrase(),
                        "错误代码:" + status,
                        Messages.getInformationIcon()
                );
            }
        } catch (IOException e) {
            //显示异常信息
            Messages.showMessageDialog(
                    e.getMessage(),
                    "啊欧,崩溃了",
                    Messages.getInformationIcon()
            );
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成URI
     *
     * @param query 查询内容
     * @return URI
     * @throws URISyntaxException
     */
    private URI createTranslationURI(String query) throws URISyntaxException {

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http")
                .setHost(HOST)
                .setPath(PATH)
                .addParameter(PARAM_KEY_FROM, KEY_FROM)
                .addParameter(PARAM_KEY, KEY)
                .addParameter(PARAM_TYPE, TYPE)
                .addParameter(PARAM_VERSION, VERSION)
                .addParameter(PARAM_DOC_TYPE, DOC_TYPE)
                .addParameter(PARAM_CALL_BACK, CALL_BACK)
                .addParameter(PARAM_QUERY, query)
        ;
        return builder.build();
    }
十、部署

Builde->Prepare Plgin Module ‘MyTranslation’For Deployment,就会在工程目录下生成MyTranslation.zip文件。然后,settings->Plugins->Install Plugin from Disk,找到刚才生成的文件安装即可,安装完重启,看看效果。


效果图 :


界面比较挫,音标还出现乱码,还好能用。

源码地址:https://github.com/loucyin/MyTranslation


©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值