如何将字符串从一种语言翻译成另一种语言

时间:2018-01-04 07:12:03

标签: android clipboard

我试图创建一个应用程序,我可以在其中翻译剪贴板中的字符串并将其显示为Toast但它在主要的异常情况下为我提供了网络。这是我的代码

@Override
protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    final ClipboardManager cb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    cb.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener(){

            @Override
            public void onPrimaryClipChanged()
            {
                // TODO: Implement this method
                ClipData clipdata = cb.getPrimaryClip();
                ClipData.Item item = clipdata.getItemAt(0);
                if(item.getText()!=null)
                {
                    //String text = item.getText().toString();
                    //Toast.makeText(getApplicationContext(), "Copied "+item.getText().toString(), Toast.LENGTH_LONG).show();
                    Translator translate = Translator.getInstance();
                    String demo = translate.translate(item.getText().toString(), Language.ENGLISH, Language.HINDI);
                    Toast.makeText(getApplicationContext(), "Translation: " + demo, Toast.LENGTH_LONG).show();
                }
            }
        });
}

1 个答案:

答案 0 :(得分:0)

您正在使用的库正在进行Web服务调用。以下代码负责服务调用。

Translator translate = Translator.getInstance();
translate.translate(strings[0], Language.ENGLISH, Language.HINDI);

您可以在AsyncTask之类的单独线程中执行此操作。尝试以下代码希望这会有所帮助。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final String temp;

    final ClipboardManager cb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    cb.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener(){

        @Override
        public void onPrimaryClipChanged()
        {
            // TODO: Implement this method
            ClipData clipdata = cb.getPrimaryClip();
            ClipData.Item item = clipdata.getItemAt(0);
            if (item != null)
            {
                String text = item.getText().toString();
                // I have used the async task here for the network call.
                new Asynch().execute(text);

            }
        }
    });
}

class Asynch extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... strings) {
        Translator translate = Translator.getInstance();
        return translate.translate(strings[0], Language.ENGLISH, Language.HINDI);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Toast.makeText(getApplicationContext(), "Translation: " + s, Toast.LENGTH_LONG).show();
    }

}