静态void main中的TextView

时间:2019-01-28 09:43:27

标签: java android static

所以我试图获取翻译后的文本并在textview中显示。
我该怎么办?而且我注意到翻译器必须在静态void main中使用它。如果没有,则会发生问题。
(java初学者)

array = ['apples', 'bananas', 'tofu', 'cats']

def commaCode (array):

    print("'"+ array[0]+',',end= '') #this line for the first element

    for i in range (1,len(array)-1): #iteration for the elements from 1 until n-1
        print(array[i]+',',end='')

    print('and '+array[-1]+"'") #this for the last element

commaCode(array)

2 个答案:

答案 0 :(得分:1)

Android不需要像Java Apps中那样执行main()方法。
而且您也不需要编写这些http调用来转换字符串值。
Android为您提供了一个string.xml文件,您可以在其中创建自己的文件WRT以进行本地化,但是键入的字符串应该相同,并且可以将其分配给textview。

答案 1 :(得分:1)

使用类似这样的东西。

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

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);
    String text = "Hello world!";
    new TransText(text).execute();
}


private 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();
}

private class TransText extends AsyncTask<Void, Void, String> {
    String text;

    public TransText(String text) {
        this.text = text;
    }

    @Override
    protected String doInBackground(Void... voids) {
        String result = null;
        try {
            result = translate("en", "zh-CN", text);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if(result != null){
            TText.setText(result);
        }
    }
}
}