我想要製作一個包含翻譯功能的APP,上網爬文後找到可以利用google translate API來達到翻譯的效果,使用以下程式碼在Activity中可以正常執行,想請問若是想在fragment中執行的話要如何修改呢?
class MainActivity : AppCompatActivity() {
private var translate: Translate? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
translateButton.setOnClickListener {
if (checkInternetConnection()) {
//If there is internet connection, get translate service and start translation:
getTranslateService()
translate()
} else {
//If not, display "no connection" warning:
translatedTv!!.text = resources.getString(R.string.no_connection)
}
}
}
private fun getTranslateService() {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
try {
resources.openRawResource(R.raw.credentials).use { `is` ->
val myCredentials = GoogleCredentials.fromStream(`is`)
val translateOptions = TranslateOptions.newBuilder().setCredentials(myCredentials).build()
translate = translateOptions.service
}
} catch (ioe: IOException) {
ioe.printStackTrace()
}
}
private fun translate() {
//Get input text to be translated:
val originalText: String = inputToTranslate!!.text.toString()
val translation = translate!!.translate(originalText, Translate.TranslateOption.targetLanguage("tr"), Translate.TranslateOption.model("base"))
//Translated text and original text are set to TextViews:
translatedTv!!.text = translation.translatedText
}
private fun checkInternetConnection(): Boolean {
//Check internet connection:
val connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = connectivityManager.activeNetworkInfo
//Means that we are connected to a network (mobile or wi-fi)
return activeNetwork?.isConnected == true
}
}