教你在APP中嵌入翻译功能,不借助第三方软件

来源:互联网 发布:上海汇纳网络信息科技 编辑:程序博客网 时间:2024/05/14 08:23

对于翻译软件大家都应该使用过,有没有想到将翻译功能直接嵌入到自己的APP中,比如聊天界面,翻译几句话的功能。正好项目由此需求,看了看有道对外提供的接口,原来很简单。

一、效果图

有道翻译.gif
说明:由于使用的是模拟器演示,没有设置输入中文,就只能看到翻译英文。需要说明的是,我没有设置搜索按钮,就通过设置键盘的回车键来搜索了。

有道翻译手机截图.png

说明:这张是手机真机截图,为了看翻译中文的效果。

二、需要在有道上面做的事情

1,打开网址:有道注册key网址

2,填写信息

有道翻译信息填写.jpg

3,下图是我填的样例

有道翻译API.jpg

说明:这里的key和网址我涂掉了,就这样通过就可以,并不需要在项目中配置什么信息。

三、代码

1,布局

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin">    <EditText        android:id="@+id/et_input"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="20dp"        android:background="@null"        android:hint="请输入要查询的内容"        android:imeOptions="actionSearch"        android:lines="1"        android:singleLine="true" />    <TextView        android:id="@+id/tv_main"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="时刻准备给您显示" /></RelativeLayout>

2,首页Java代码

package com.example.mjj.useyoudaodemo;import android.content.Context;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.KeyEvent;import android.view.inputmethod.EditorInfo;import android.view.inputmethod.InputMethodManager;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import com.mjj.baseapp.http.OkHttpUtils;import com.mjj.baseapp.http.callback.StringCallback;import com.mjj.baseapp.json.GsonUtil;import okhttp3.Call;/** * Description:嵌入有道翻译API * <p> * Created by Mjj on 2016/12/19. */public class MainActivity extends AppCompatActivity {    private EditText editText;    private TextView textView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        initView();    }    private void initView() {        setContentView(R.layout.activity_main);        editText = (EditText) findViewById(R.id.et_input);        textView = (TextView) findViewById(R.id.tv_main);        // 利用键盘的按钮搜索        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {            @Override            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {                if (i == EditorInfo.IME_ACTION_SEARCH) {                    // 先隐藏键盘                    ((InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))                            .hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(),                                    InputMethodManager.HIDE_NOT_ALWAYS);                    httpData();                    return true;                }                return false;            }        });    }    private void httpData() {        OkHttpUtils.get()                .url("http://fanyi.youdao.com/openapi.do?")                .addParams("keyfrom", "UseYouDaoDemo")                .addParams("key", "829332419")                .addParams("type", "data")                .addParams("doctype", "json")                .addParams("version", "1.1")                .addParams("q", editText.getText().toString().trim())                .build()                .execute(new StringCallback() {                    @Override                    public void onError(Call call, Exception e, int id) {                        Toast.makeText(MainActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();                    }                    @Override                    public void onResponse(String response, int id) {                        GsonUtil gsonutil = new GsonUtil();                        TranslateBean bean = gsonutil.getJsonObject(response, TranslateBean.class);                        if (null != bean) {                            int errorCode = bean.getErrorCode();                            if (errorCode == 20) {                                Toast.makeText(MainActivity.this, "要翻译的文本过长", Toast.LENGTH_SHORT).show();                            } else if (errorCode == 40) {                                Toast.makeText(MainActivity.this, "不支持该语言", Toast.LENGTH_SHORT).show();                            } else if (errorCode == 0) {                                textView.setText("");                                textView.setText(bean.getTranslation().get(0));                            }                        }                    }                });    }}

说明:这里对键盘的回车键做了搜索功能,网络请求使用OKhttp,数据解析Gson。

3、返回值

有道翻译返回信息说明.jpg

说明:其中doctype是指定你希望返回的数据格式;type为固定值;errorCode返回0表示正常请求。

code小生寄语:
源码已上传至github,公众号回复 “demo” 查看链接。本篇是code小生的第二篇原创文章,倍感欣喜。时至今日,2016即将过去,距离程序猿放假回家过年的日子也就一个月,所以这段时间里,code小生决定学习一下2016年好的开源项目,汲取其中的精华,推送给各位朋友,一起学习。

技术分享公众号.jpg

1 0