【发布时间】:2019-06-21 06:54:33
【问题描述】:
所以我正在尝试获取翻译后的文本并将其显示在我的文本视图中。
我该怎么做?而且我注意到翻译必须在静态 void main 中使用它...如果不是会出现问题。
(java初学者)
public class TranslateText extends AppCompatActivity {
TextView TText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_translate_text);
TText = findViewById(R.id.TranslatedView);
}
public static void main(String[] args) throws IOException {
String text = "Hello world!";
System.out.println("Translated text: " + translate("en", "zh-CN",text));
}
private static String translate(String langFrom, String langTo, String text) throws IOException {
String urlStr = "https://script.google.com/macros/s/AKfycbzjyCsF9eoo7MR38wVg0WFU9oxc9I2aU4Bt4YPEiqtRLJLx0XU/exec" +
"?q=" + URLEncoder.encode(text, "UTF-8") +
"&target=" + langTo +
"&source=" + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
【问题讨论】:
-
你为什么在 android 应用中使用 public static void main(String[] args){}?
-
我指的是这里 - stackoverflow.com/a/48159904/9589884 我正在做翻译的事情,如果 translate("en", "zh-CN",text) 在公共静态之外,它就不起作用无效的主要。 @GaneshGudghe
-
那么无论如何我可以使用翻译文本(zh-CN)并在我的文本视图中显示它吗?
-
使用 asyntask 并在 doinbackground 中执行你的 translate()